RobertJoseph RobertJoseph - 5 months ago 9
Swift Question

Why doesn't a class have to provide a failable inititalizer if it implements a protocol that declares one?

I am trying to understand the following, contrived, example:

protocol MyProtocol {
init?(string: String)
}

class MyObject: MyProtocol {
let s: String
required init(string: String) {
self.s = string
}
}

let o = MyObject(string: "test")
print(o.s)


MyProtocol
declares a failable initializer.
MyObject
conforms to
MyProtocol
and the example code compiles and executes without issue.

My question is: Why doesn't
MyObject
have to provide a failable initializer (as per
MyProtocol
)?

Answer

This is for the same reason that this compiles:

class A {
    init?(s:String) {}
    init() {}
}
class B : A {
    override init(s:String) {super.init()}
}

init can override (i.e. be substituted for) init?.

See also the docs (when something is so clearly documented, it seems silly to ask "why"; it's just a fact about the language):

A failable initializer requirement can be satisfied by a failable or nonfailable initializer on a conforming type.