考虑这个枚举...
enum ServiceValue : String, Decodable {
case a
case b
case c
case other
}
给出一个字符串' a'你可以得到一个枚举实例,如下:
// 'value' is an optional since the initializer is bailable
let value = ServiceValue(rawValue:'a')
我们要做的不是回归“没有”。对于未知值,例如' d'或者' somethingUnknown',我们想要返回ServiceValue.other
。但是,您不能覆盖初始化程序,因为它不在基类中,而是为此枚举本身生成编译器。
那就是说,我们试着滚动自己,就像这样......
init(serviceValue:String){
self.init(rawValue:serviceValue) ?? self.init(rawValue:"other")
}
...但是这并没有解决以下错误:
不可用的初始化程序无法委托给可用的初始化程序" init(rawValue :)'写着' init?'
和
初始化程序委派(' self.init')不能嵌套在另一个表达式中
当然我可以简单地写一个静态方法initFrom
,就像这样......
initFrom(serviceValue:String) -> ServiceValue {
return ServiceValue(rawValue:serviceValue) ?? ServiceValue(rawValue:"other")
}
...但这是一种工厂方法,而不是真正的初始化程序,也不能防止仍然使用init(rawValue:
的人(虽然也许最后一部分是好的,因为它会改变预期的行为。一个完美的世界,我只是完全隐藏了初始化程序,但同样,你不能覆盖枚举中的初始化程序。)
这样可以实现,还是工厂模式是唯一的出路?
答案 0 :(得分:2)
您可以使用默认值创建自定义非易错初始化程序,如下所示:
init(string: String) {
self = ServiceValue(rawValue: string) ?? .other
}