简体   繁体   中英

How to satisfy a protocol which includes an initializer?

I defined a simple class:

class MyClass {
    var name:String?

    required init() {
        println("init")
    }
}

I can add a new initializer in an extension like this:

extension MyClass {
    convenience init(name: String) {
        self.init()
        self.name = name
    }
}

Everything works fine.

But as soon as I define the new initializer in a protocol:

protocol MyProtocol {
    init(name:String)
}

And make my extension confirm to that protocol:

extension MyClass : MyProtocol {
    convenience init(name: String) {
        self.init()
        self.name = name
    }
}

I get the following error:

Initializer requirement 'init(name:)' can only be satisfied by a required initializer in the definition of non-final class 'MyClass'

What is going on here?

(BTW: I can't make my class final , because this is only the extract of a more complicated use case.)

Ok, my bad.

To guarantee that all subclasses conform to MyProtocol new initializer has to be marked as required as well.

Furthermore Swift requires to declare all required initializers directly within the class and does not allow to declare them in extensions.

extension MyClass : MyProtocol {
    required convenience init(name: String) {
        self.init()
        self.name = name
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM