加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 具有非可选属性的便捷初始化程序

发布时间:2020-12-14 04:47:41 所属栏目:百科 来源:网络整理
导读:我的一个对象有一个整数ID.由于这是一个必需的属性,我没有将它定义为可选,我要求它在指定的初始化程序中: class Thing { var uniqueID: Int var name: String? init (uniqueID: Int) { self.uniqueID = uniqueID } } 由于我是从一些JSON创建其中一个,因此用
我的一个对象有一个整数ID.由于这是一个必需的属性,我没有将它定义为可选,我要求它在指定的初始化程序中:

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])

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读