ios - Swift 枚举 : normal/non failable initializers not supported - or just broken?

标签 ios xcode swift enums xcode6

我已阅读有关 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/

相关文章:

ios - PubNub 发布订阅如何在 iOS 内部工作(客户端)

xcode - XCTest不将新方法注册为测试

xcode - 模块 bolt 的伞头不包括头 'BFAppLinkResolving.h'

ios - 如何在 Swift 中获取 'expected' 类型的 CoreData 属性?

ios - 无法在 Swift 的 UITextFieldDelegate 类初始值设定项中使用 TextField

iOS UIAlertView 权限 Alpha 阴影

php - PHP 加密与 iOS 和 .NET 的区别

ios - UITableView 上未调用长按手势

swift - 在 iOS Swift 中流式传输 Spotify Preview_url

iphone - 在单个 UIViewController 中有多个 UIView 的障碍