在 Swift 中处理初始化失败
Handling initialisation failure in Swift
我有一个自定义 class,我想使用 JSONCodable https://github.com/matthewcheok/JSONCodable
从 JSON 对象初始化
所以我有
public var id: String
public var name: String?
public var imageURL: NSURL?
和一个符合 JSONCodable 协议
的可失败初始化器
required public init?(JSONDictionary: JSONObject) {
let decoder = JSONDecoder(object: JSONDictionary)
do {
id = try decoder.decode("id")
name = try decoder.decode("name")
if let imageURLString: String = try decoder.decode("image") {
imageURL = NSURL(string: imageURLString)
}
}
catch let error as NSError{
NSLog("\(error.localizedDescription)")
return nil
}
}
我在 'Return nil' 语句中遇到编译器错误:
class 实例的所有存储属性必须在从初始化程序返回 nil 之前初始化。
除了设置虚拟值之外,有没有办法解决这个问题?我想包含的属性之一是只读的,我真的不想创建一个 setter 来绕过编译器。
我使用的是 class,而不是 JSONCodable 示例代码中的结构,因为我想子 class。
一种可能性是有一个非失败的初始化器,它会抛出一个错误,但这不符合 JSONCodable 协议。
我是 Swift 的新手,非常欢迎任何有关如何处理此问题的指示。
借助此答案修复:Best practice to implement a failable initializer in Swift (mentioned here https://github.com/matthewcheok/JSONCodable/issues/5)
所以现在我有
public var id: String!
id 现在已隐式解包,因此它的默认值为 nil。
我有一个自定义 class,我想使用 JSONCodable https://github.com/matthewcheok/JSONCodable
从 JSON 对象初始化所以我有
public var id: String
public var name: String?
public var imageURL: NSURL?
和一个符合 JSONCodable 协议
的可失败初始化器required public init?(JSONDictionary: JSONObject) {
let decoder = JSONDecoder(object: JSONDictionary)
do {
id = try decoder.decode("id")
name = try decoder.decode("name")
if let imageURLString: String = try decoder.decode("image") {
imageURL = NSURL(string: imageURLString)
}
}
catch let error as NSError{
NSLog("\(error.localizedDescription)")
return nil
}
}
我在 'Return nil' 语句中遇到编译器错误: class 实例的所有存储属性必须在从初始化程序返回 nil 之前初始化。 除了设置虚拟值之外,有没有办法解决这个问题?我想包含的属性之一是只读的,我真的不想创建一个 setter 来绕过编译器。 我使用的是 class,而不是 JSONCodable 示例代码中的结构,因为我想子 class。 一种可能性是有一个非失败的初始化器,它会抛出一个错误,但这不符合 JSONCodable 协议。 我是 Swift 的新手,非常欢迎任何有关如何处理此问题的指示。
借助此答案修复:Best practice to implement a failable initializer in Swift (mentioned here https://github.com/matthewcheok/JSONCodable/issues/5)
所以现在我有
public var id: String!
id 现在已隐式解包,因此它的默认值为 nil。