I would like to specify a default implementation for an initializer in a protocol, so that I can run code on all structs conforming to a specific protocol.
I have the following example:
protocol ProtWithInit {
init()
}
extension ProtWithInit {
init() {
self.init()
print("Hello protocol")
}
}
struct MyStruct {}
extension MyStruct: ProtWithInit {}
let myStruct = MyStruct()
What I would like the MyStruct()
call to do, is output "Hello protocol". However, nothing is being outputted when I run the above code.
Additionally, I would like to add to the initializer in the struct. So for example in the struct I add print("Hello struct")
to the initializer and this would then outut both hello protocol
and hello struct
.
Is there any way I can achieve this?
CodePudding user response:
This, if it did anything, would be an infinite loop:
extension ProtWithInit {
init() {
self.init()
print("Hello protocol")
}
}
Structs and protocols are not classes. They do not have class-like inheritance. (Even if this were a class, this would be an infinite loop, since self.init()
would just call init()
again.)
Go back to your calling code, the code you say "so that I can run code on all structs conforming to a specific protocol." What do that code look like. What does it actually require on real types? Use that to work out your protocol. For example, the following would be similar to what you're describing:
extension ProtWithInit {
static func create() -> Self {
print("Hello protocol")
return Self.init()
}
}
let myStruct = MyStruct.create()