大佬教程收集整理的这篇文章主要介绍了swift – 具有非可选属性的便捷初始化程序,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
class Thing { var uniquEID: Int var name: String? init (uniquEID: int) { self.uniquEID = uniquEID } }
if let uniquEID = DictionarY["id"] as? Int { let thing = thing(uniquEID: uniquE) }
(顺便说一句,我希望对我到目前为止所做的事情进行健全检查).
接下来,我希望能够为Thing类添加一个便利初始化器,它接受字典对象并相应地设置属性.这包括所需的uniquEID和一些其他可选属性.到目前为止,我的最大努力是:
convenience init (Dictionary: [String: AnyObject]) { if let uniquEID = DictionarY["id"] as? Int { self.init(uniquEID: uniquEID) //set other values here? } //or here? }
但是当然这还不够,因为没有在条件的所有路径上调用指定的初始值设定项.
我该如何处理这种情况?它甚至可能吗?或者我应该接受uniquEID必须是可选的吗?
convenience init?(Dictionary: [String: AnyObject]) { if let uniquEID = DictionarY["id"] as? Int { self.init(uniquEID: uniquEID) } else { self.init(uniquEID: -1) return nil } }
从技术上讲,这可以稍微调整一下(主要取决于你的喜好/ swift版本),但我的人选择如下:
class func fromDictionary(Dictionary: [String: AnyObject]) -> Thing? { if let uniquEID = DictionarY["id"] as? Int { return self.init(uniquEID: uniquEID) } return nil }
所有在一起,作为一个操场:
class Thing { var uniquEID: Int var name: String? init(uniquEID: int) { self.uniquEID = uniquEID } convenience init?(Dictionary: [String: AnyObject]) { if let uniquEID = DictionarY["id"] as? Int { self.init(uniquEID: uniquEID) } else { self.init(uniquEID: -1) return nil } } class func fromDictionary(Dictionary: [String: AnyObject]) -> Thing? { if let uniquEID = DictionarY["id"] as? Int { return self.init(uniquEID: uniquEID) } return nil } } let firstThing = Thing(uniquEID: 1) let secondThing = Thing(Dictionary: ["id": 2]) let thirdThing = Thing(Dictionary: ["not_id": 3]) let forthThing = Thing.fromDictionary(["id": 4]) let fithThing = Thing.fromDictionary(["not_id": 4])
以上是大佬教程为你收集整理的swift – 具有非可选属性的便捷初始化程序全部内容,希望文章能够帮你解决swift – 具有非可选属性的便捷初始化程序所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。