我创建了示例应用程序来测试可失败的初始化程序。当我扩展 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
}
}
屏幕截图
最佳答案
所有属性必须在 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/