Handling class initialization failure in Swift extension

末鹿安然 提交于 2019-12-05 00:40:39

You can now create failable initializers in extensions; however, the initializers can not be defined in a protocol.

class Thing {

    var text:String?

}

extension Thing  {

    convenience init?(text:String) {
        self.init()
        if text == "" {
            return nil
        } else {
            self.text = text
        }
    }
}


let that = Thing(text: "Hello")
println(that?.text) //prints Optional("Hello")

let empty = Thing(text: "")
println(empty) //prints nil

Unlike Objective-C, Swift initializers don't return self, so checking for initialization failures is not possible. An Apple engineer suggested using a factory method with an optional return type instead:

class ImageFactory {

    class func validImage(named name: String) -> UIImage? 
    {
        var image = UIImage(named:name)
        assert(image != nil, "fail")
        return image;
    }
}

The Apple engineer indicated that they are working on building something into the language that will get around using factory class methods.

Areal-17

i would write the method like below:

extension UIImage {

class func validImage(named name: String) -> UIImage? {
    var image = UIImage(named: name)
    return image
}

in swift you can use optionals. If here is no image with the given name the method will return nil.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!