如何使以下调用中的属性可选(即允许nil)
很长一段时间,因为我已经写了iOS代码,但我有一个iOS应用程序中的以下模型,工程很好,但现在我们发现detail
是可选的,我们应该允许零值。 我将如何调整初始值设定器来支持这个? 对不起,我觉得可选项有点难以理解(概念是有道理的 – 执行起来很困难)。
class Item{ var id:Int var header:String var detail:String init?(dictionary: [String: AnyObject]) { guard let id = dictionary["id"] as? Int, let header = dictionary["header"] as? String, let detail = dictionary["detail"] as? String else { return nil } self.id = id self.header = header self.detail = detail }
并创造:
var items = [Item]() if let item = Item(dictionary: dictionary) { self.items.append(item) }
正如上面的@AMomchilov的答案,只有当它存在于你的init
方法中时,才可以赋值。 但也可以检查值,然后像下面这样访问它:
class Item { var id:Int var header:String var detail: String? init?(dictionary: [String: AnyObject]) { guard let id = dictionary["id"] as? Int, let header = dictionary["header"] as? String else { return nil } self.id = id self.header = header self.detail = dictionary["detail"] as? String //if there is value then it will assign else nil will be assigned. } } let dictionary = ["id": 10, "header": "HeaderValue"] var items = [Item]() if let item = Item(dictionary: dictionary) { items.append(item) print(item.id) print(item.detail ?? "'detail' is nil for this item") print(item.header) }else{ print("No Item created!") }
和控制台是:
10 'detail' is nil for this item HeaderValue
如果有“细节”价值,那么:
let dictionary = ["id": 10, "header": "HeaderValue", "detail":"DetailValue"] var items = [Item]() if let item = Item(dictionary: dictionary) { items.append(item) print(item.id) print(item.detail ?? "'detail' is nil for this item") print(item.header) }else{ print("No Item created!") }
安慰:
10 DetailValue HeaderValue
从警卫中删除detail
(因为现在可以接受一个nil
值),并将self.detail
给dictionary["detail"] as? String
dictionary["detail"] as? String
。
class Item { var id: Int var header: String var detail: String? init?(dictionary: [String: AnyObject]) { guard let id = dictionary["id"] as? Int, let header = dictionary["header"] as? String else { return nil } self.id = id self.header = header self.detail = dictionary["detail"] as? String }
编辑:基于Santosh的答案改进。