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:

  1. The protocol and the class that implements it, never have the keyword func in front of the init method.
  2. In your class, since the init method was called out in your protocol, you now need to prefix the init method with the keyword required. This indicates that a protocol you conform to required you to have this init 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.

Share:
35,013
Aaron Bratcher
Author by

Aaron Bratcher

Updated on July 05, 2022

Comments

  • Aaron Bratcher
    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
    LiweiZ over 9 years
    Can you explain the reason for not putting func in front of init? Thanks.
  • newacct
    newacct over 9 years
    @LiweiZ: because initializers and methods are separate
  • LiweiZ
    LiweiZ over 9 years
    Thank you. I guess I need to go through the developer docs one more time:)
  • Jay Imerman
    Jay Imerman almost 9 years
    OK, Swift is known for its style consistencies, and this is very inconsistent and confusing to newbs. Thanks for the answer.