iTranslated by AI
The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🕊
[Swift] Enums with rawValue automatically receive an initializer
Enums with rawValue automatically get an initializer defined
I didn't know this until recently. It is clearly stated on swift.org.
Initializing from a Raw Value
If you define an enumeration with a raw-value type, the enumeration automatically receives an initializer that takes a value of the raw value’s type (as a parameter called rawValue) and returns either an enumeration case or nil. You can use this initializer to try to create a new instance of the enumeration.
Let's verify the behavior in practice
enum Drink: String {
case coffee
case tea
}
print(Drink(rawValue: "coffee") ?? "Undefined") // coffee
print(Drink(rawValue: "tea") ?? "Undefined") // tea
print(Drink(rawValue: "hoge") ?? "Undefined") // Undefined
It seems an initializer like the one below is defined automatically.
enum Drink: String {
case coffee
case tea
// This is automatically defined
init?(rawValue: String) {
switch rawValue {
case Drink.coffee.rawValue:
self = .coffee
case Drink.tea.rawValue:
self = .tea
default:
return nil
}
}
}
Honestly, I think there are limited use cases for this, as most scenarios can be handled by extending the enum definition.
It also feels a bit cumbersome to use because you must account for the fact that the initializer returns nil if there is no matching rawValue.
That's all.
Discussion