Reputation: 1457
I have a simple enum of type string:
enum MyEnum: String {
case hello = "hello"
case world = "world"
}
And I want to write a case-insensitive constructor. I tried this (with or without extension):
init?(string: String) {
return self.init(rawValue: string.lowercased())
}
but I get an error saying:
'nil' is the only value permitted in an initializer
Upvotes: 0
Views: 906
Reputation: 63399
You don't need to return
anything. You just call initializer:
enum MyEnum: String {
case hello = "hello"
case world = "world"
init?(caseInsensitive string: String) {
self.init(rawValue: string.lowercased())
}
}
print(MyEnum(caseInsensitive: "HELLO") as Any) // => Optional(Untitled.MyEnum.hello)
print(MyEnum(caseInsensitive: "Goodbye") as Any) // => nil
Upvotes: 3