iGodric iGodric - 2 years ago 68
Swift Question

Self in protocol always need to be optional?

Example:

internal protocol PropertyProtocol {
var property: Self {
get
}
}


The only option I see to implement it, let us say in a class is

internal final class PropertyClass: PropertyProtocol {
let property: PropertyClass

internal init(otherOne pOtherOne: PropertyClass) {
self.property = pOtherOne
}
}


But then I do not see a possibility to use it.

let test: PropertyProtocol = PropertyProtocol(...) // hmm, how?


Does Self in a protocol property type declaration always have to be optional?

Answer Source

As a stored property, indeed it would have to be optional for you to create an instance, as each instance would require the stored property to be assigned during initialisation – leading to recursive behaviour. Therefore Self doesn't make too much sense as a stored property; it's really more designed to be used with methods or calculated properties.

Depending on what you're using this for (seems like a fairly hypothetical example), you could implement a calculated property like so:

protocol PropertyProtocol {
    var property : Self { get }
}

final class PropertyClass : PropertyProtocol {
    var property : PropertyClass {
        get {
            return // ...
        }
        set {
            // ...
        }
    }
}

That way the class itself can manage the creation of the property when it's accessed, preventing the recursive behaviour of requiring it to be assigned during initialisation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download