Can I have an init func in a protocol?

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?


Yes you can. But you never put func in front of init:

protocol Serialization {
    init(key keyValue: String, jsonValue: String)
}

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.