Swift protocol extension self reference issues with init

7.7k Views Asked by At

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?

enter image description here

1

There are 1 best solutions below

0
On BEST ANSWER

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.