Why should a class not provide a failed initializer if it implements a protocol that declares it?

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(os) 

MyProtocol announces a failable initializer . MyObject corresponds to MyProtocol , and the sample code compiles and runs without problems.

My question is: why does MyObject not have to provide an initializer with an error (according to MyProtocol )?

+5
source share
1 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. replace) init? .

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

The initializer fault tolerance requirement can be met with an initializer with an error or an invalid type on the corresponding type.

(As pointed out in the comments on the question and answers, this makes sense if you think about the difference between init? Which never breaks and init with the same signature, namely: there is no effective difference. In other words: you can tell me that I can fail, but you cannot tell me that I must fail.)

+6
source

All Articles