Can I have an init func in a protocol?
Yes you can. But you never put func
in front of init
:
protocol Serialization {
init(key keyValue: String, jsonValue: String)
}
Key points here:
- The protocol and the class that implements it, never have the keyword
func
in front of theinit
method. - In your class, since the
init
method was called out in your protocol, you now need to prefix theinit
method with the keywordrequired
. This indicates that a protocol you conform to required you to have thisinit
method (even though you may have independently thought that it was a great idea).
As covered by others, your protocol would look like this:
protocol Serialization {
init(key keyValue: String, jsonValue: String)
}
And as an example, a class that conforms to this protocol might look like so:
class Person: Serialization {
required init(key keyValue: String, jsonValue: String) {
// your logic here
}
}
Notice the required keyword in front of the init
method.