Protocol private(set) properties

I would like to prevent write access from outside my class to a property defined by protocol conformance.

protocol MutableClientProtocol {
    associatedType Client

    var client: Client { get private(set) }
    mutating func setClient(_ newClient: Client)
}

Do you think this is possible in some form with protocols?

A protocol is a statement about the minimum capabilities of a type, and it cannot really restrict the type to having a private setter. From the point of view of someone using the protocol, this is no different than if the protocol declared a { get } requirement, which cannot prevent the conforming type from having a setter, private or public.

7 Likes

I agree with you, but you are describing the current state of protocol in swift. Do you mind if there's any intention to provide such kind of feature in future?

Such features were discussed in topics about abstract classes if I remember correctly. Abstract classes were deferred though. There were also discussions about private protocol requirements.

Why can't the following minimum capability be valid:

This conforming type has a variable that you can get and but may be set privately.

If we ever get type(set) or something equivalent, then I think this could be a powerful feature.

How would usage differ between the protocol you’ve written and one where the private(set) is simply absent from the protocol requirements?

1 Like

Simply in a protocol extension mutating func doesn’t work if property is { get } only, this mean u can’t provide a default method your own protocols. @Jumhyn