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