Swift 2.1:扩展NSObject时获取错误

时间:2016-03-01 12:21:45

标签: swift2 nsobject xcode7.2

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

  

1)属性'self.userName'未在super.init调用时初始化。
2)   不可变值'self.userDetails'只能初始化一次。
3)   不可变值'self.userName'只能初始化一次。

请查看以下代码和截图。

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

2 个答案:

答案 0 :(得分:1)

所有属性必须在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
        }
    }
}

答案 1 :(得分:1)

import Foundation

let dictionary = ["user_name": "user", "user_Details":[1,2,3]]

class User: NSObject {

    var userName: String?
    var 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
    }        
}

let c = User(dictionary: dictionary)
dump(c)
/*
▿ User
  ▿ Some: User #0
    - super: <__lldb_expr_31.User: 0x7fe372f15860>
    ▿ userName: user
      - Some: user
    - userDetails: nil
*/