带有自定义构造函数的Swift枚举



我有一个字符串类型的简单枚举:

enum MyEnum: String {
case hello = "hello"
case world = "world"
}

我想写一个不区分大小写的构造函数。我试过这个(带或不带扩展(:

init?(string: String) {
return self.init(rawValue: string.lowercased())
}

但我得到一个错误说:

'nil' is the only value permitted in an initializer

您不需要return任何内容。您只需调用初始值设定项:

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

最新更新