Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 891
Aaron Bratcher Avatar asked Sep 05 '14 21:09

Aaron Bratcher


People also ask

Can Swift Protocol have init?

Swift allows programmers to directly initialize protocols by conforming to its types. We can declare the initializers as a part of protocol same as a normal initializer, but we won't use the curly braces or an initializer body.

What is required init in Swift?

Swift init() Initialization is the process of preparing an instance of a class, structure, or enumeration for use. This process involves setting an initial value for each stored property on that instance and performing any other setup or initialization that is required before the new instance is ready for use.

What is convenience init Swift?

Convenience initializers are secondary, supporting initializers for a class. You can define a convenience initializer to call a designated initializer from the same class as the convenience initializer with some of the designated initializer's parameters set to default values.

What is protocol extension in Swift?

In Swift, you can even extend a protocol to provide implementations of its requirements or add additional functionality that conforming types can take advantage of. For more details, see Protocol Extensions. Note. Extensions can add new functionality to a type, but they can't override existing functionality.


2 Answers

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

protocol Serialization {     init(key keyValue: String, jsonValue: String) } 
like image 137
newacct Avatar answered Oct 01 '22 21:10

newacct


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.

like image 30
idStar Avatar answered Oct 01 '22 22:10

idStar