我已阅读有关 Swift 的文档 failable initializer's但没有看到任何关于正常的、不会失败的品种的明确信息。我是否错过了什么,或者具有原始值的枚举器不支持常规初始化程序,即使初始化程序不可能失败(因为初始化程序遵循默认值):
enum FailableSeason : Int {
init?(d: Int) {
switch (d % 365) {
case 60...151:
self = .Spring
case 152...243:
self = .Summer
case 244...334:
self = .Fall
// default provided, guaranteed to be valid
default:
self = .Winter
}
}
case Spring
case Summer
case Fall
case Winter
}
enum ImplicitlyUnwrappedFailableSeason : Int {
init!(d: Int) {
switch (d % 365) {
case 60...151:
self = .Spring
case 152...243:
self = .Summer
case 244...334:
self = .Fall
// default provided, guaranteed to be valid
default:
self = .Winter
}
}
case Spring
case Summer
case Fall
case Winter
}
enum NonFailableSeason : Int {
init(d: Int) {
switch (d % 365) {
case 60...151:
self = .Spring
case 152...243:
self = .Summer
case 244...334:
self = .Fall
// default provided, guaranteed to be valid
default:
self = .Winter
}
}
case Spring
case Summer
case Fall
case Winter
}
let thisWorks = FailableSeason(d: 60)
let thisFails = ImplicitlyUnwrappedFailableSeason(d: 60)
let andThisFails = NonFailableSeason(d: 0)
请注意,我将其分解为单独的枚举,以确保这不是初始化程序冲突的问题。
最佳答案
这曾经适用于 Swift 1.1 (Xcode 6.1.1),但在 Swift 1.2 (Xcode 6.3) 中失败。 这是一个已在 Apple 开发者论坛中讨论过的错误:Swift 1.2 - Initializing Enums .
该讨论中给出了两种解决方法:使用模块/应用程序名称 作为前缀:
let workaround1 = NameOfYourModule.NonFailableSeason(d: 0)
或者显式调用init方法:
let workaround2 = NonFailableSeason.init(d: 0)
更新:这已在 Xcode 6.3 beta 2 (6D532l) 版本中修复。
关于ios - Swift 枚举 : normal/non failable initializers not supported - or just broken?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28653484/