Search code examples
swiftoption-typeinit

Swift unwrap optional init inside convenience init


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
    }
}

Solution

  • 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.