Can I have an init func in a protocol?

SwiftInitializationProtocolsSwift Protocols

Swift Problem Overview


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?

Swift Solutions


Solution 1 - Swift

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

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

Solution 2 - Swift

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAaron BratcherView Question on Stackoverflow
Solution 1 - SwiftnewacctView Answer on Stackoverflow
Solution 2 - SwiftidStarView Answer on Stackoverflow