I'm looking for a way to add a default initializer to a protocol via protocol extensions.
My protocol is:
protocol TestProtocol {
var myVar : Double { get set }
init(value: Double)
init(existingStruct : TestProtocol)
}
I've implemented a struct using this protocol as:
struct TestStruct : TestProtocol {
var myVar : Double
init(value : Double) {
myVar = value
}
init (existingStruct : TestProtocol) {
myVar = existingStruct.myVar
}
}
However if I try via extension to make a default initializer for this protocol I run into self issues:
extension TestProtocol {
init(value : Double) {
myVar = value
}
init(existingStruct : TestProtocol) {
myVar = existingStruct.myVar
}
}
Where both assignment lines issue the error Variable 'self' passed by reference before being initialized
Is there a way to make this work - or am i limited to using classes?
Swift Protocol Initializer RequirementsSwift 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.
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. Extensions can add new functionality to a type, but they can't override existing functionality.
Initializers. Swift 4 provides the flexibility to add new initializers to an existing type by extensions. The user can add their own custom types to extend the types already defined and additional initialization options are also possible. Extensions supports only init().
Protocols let you describe what methods something should have, but don't provide the code inside. Extensions let you provide the code inside your methods, but only affect one data type – you can't add the method to lots of types at the same time.
Your question is almost the same as in this post I answered yesterday.
Here is the trick to solve this :)
protocol TestProtocol {
var myVar : Double { get set }
init() // designated initializer which will ensure that your class or structer type will instantiate correctly
}
struct TestStruct : TestProtocol {
var myVar : Double
init() {
myVar = 0
}
}
extension TestProtocol {
init(value : Double) {
self.init()
myVar = value
}
init(existingStruct : TestProtocol) {
self.init()
myVar = existingStruct.myVar
}
}
Have a good day. :) Protocol extension is so nice.
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