swift2 - swift 2.1 : Getting error while extends NSObject

标签 swift2 nsobject xcode7.2

我创建了示例应用程序来测试可失败的初始化程序。当我扩展 NSObject 时,我收到以下错误。

1) Property 'self.userName' not initialized at super.init call.
2) Immutable value 'self.userDetails' may only be initialized once.
3) Immutable value 'self.userName' may only be initialized once.

请找到以下代码和屏幕截图。

class User: NSObject {

    let userName: String!
    let userDetails: [String]?

    init?(dictionary: NSDictionary) {
        super.init()

        if let value = dictionary["user_name"] as? String {
            self.userName = value
        }
        else {
            return nil
        }

        self.userDetails = dictionary["user_Details"] as? Array
    }        
}

屏幕截图

enter image description here

最佳答案

所有属性必须在 super.init() 之前初始化

super.init() 之后,必须从可失败初始化程序返回 Nil。此限制should be removed in Swift 2.2

正确的实现是:

class User: NSObject {

    let userName: String!
    let userDetails: [String]?

    init?(dictionary: NSDictionary) {
        if let value = dictionary["user_name"] as? String {
            self.userName = value
        } else {
            self.userName = nil
        }

        self.userDetails = dictionary["user_Details"] as? Array

        super.init()

        if userName == nil {
            return nil
        }

        else if userDetails == nil {
            return nil
        }
    }
}

关于swift2 - swift 2.1 : Getting error while extends NSObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35722811/

相关文章:

swift - 带有 Swift 的 CorePlot - 将轴放在前面

swift - 在 Swift2 中如何解决这个错误?

core-data - 在 Mac 上以 UTF-8 格式保存 CSV

ios - 获取自定义 NS 对象的属性数组的简单方法?

ios - swift 2.1,Xcode 7.2。简单的新手关于为什么它在 Playground 中有效但在应用程序中不起作用

ios - xcode 7.2 中的 Google+ 集成

ios - swift2.0如何设置app locale

objective-c - 为什么继承需要是 "subclass"NSObject?

equality - Swift 2.0 中等于运算符和 NSObjects 的错误?

algorithm - 闭包参数列表的上下文类型需要 1 个参数,但指定了 2 个