微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我的一个对象有一个整数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])

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐