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 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.
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.
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.
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.
Yes you can. But you never put func
in front of init
:
protocol Serialization { init(key keyValue: String, jsonValue: String) }
Key points here:
func
in front of the init
method.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With