Home > Enterprise >  Swift unwrap optional init inside convenience init
Swift unwrap optional init inside convenience init

Time:01-04

Is it possible to unwrap optional init somehow inside convenience init?

convenience init(...) {
   self.init?(...) ?? self.init()
}

Actually, I'm trying to make convenience init for UIColor:

extension UIColor {
    convenience init(for item: ItemType) {
       self.init(named: item.rawValue) ?? self.init() // something like this
       //self.init(named: item.rawValue)! // works
    }
}

CodePudding user response:

Initializers are highly restricted in how they can speak. But factory methods are not! This compiles (and works):

extension UIColor {
    static func create(for item: ItemType) -> UIColor {
        UIColor(named: item.rawValue) ?? UIColor()
    }
}

CodePudding user response:

You cannot have such an unwrapping, because it is forbidden to delegate a non-failable initializer to a failable initializer. This is the consequence of the following language reference principle:

In either case, if you delegate to another initializer that causes initialization to fail, the entire initialization process fails immediately, and no further initialization code is executed.

  •  Tags:  
  • Related