Can I have an init func in a protocol?
35,013
Solution 1
Yes you can. But you never put func
in front of init
:
protocol Serialization {
init(key keyValue: String, jsonValue: String)
}
Solution 2
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.
![Aaron Bratcher](https://i.stack.imgur.com/gQhPR.png?s=256&g=1)
Author by
Aaron Bratcher
Updated on July 05, 2022Comments
-
Aaron Bratcher almost 2 years
When I try to implement my protocol this way:
protocol Serialization { func init(key keyValue: String, jsonValue: String) }
I get an error saying: Expected identifier in function declaration.
Why am I getting this error?
-
LiweiZ over 9 yearsCan you explain the reason for not putting func in front of init? Thanks.
-
newacct over 9 years@LiweiZ: because initializers and methods are separate
-
LiweiZ over 9 yearsThank you. I guess I need to go through the developer docs one more time:)
-
Jay Imerman almost 9 yearsOK, Swift is known for its style consistencies, and this is very inconsistent and confusing to newbs. Thanks for the answer.