RobertJoseph RobertJoseph - 1 year ago 55
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")

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

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download