class Thing { var uniqueID: Int var name: String? init (uniqueID: Int) { self.uniqueID = uniqueID } }
由于我是从一些JsON创建其中一个,因此用法如下:
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必须是可选的吗?
解决方法 你有几个选择.一个是 failable initialisers: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 – 具有非可选属性的便捷初始化程序所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)