使用自定义构造函数的Swift枚举

时间:2018-12-11 17:34:58

标签: swift enums init

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

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

1 个答案:

答案 0 :(得分:2)

您不需要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