Support for "private get / public set" ACL for properties

There was an old open discussion about having pure setters for properties, e.g. - properties that cannot be read, but only written to. It was rejected at the time, but I've actually faced a different common need that I can't express in Swift, and wonder if it's reasonable to want it to be in Swift :)

It's inline with the previous suggestion, but not really the same. Instead of having "set only" properties, it would be highly useful to have more granular ACL for the read property.

For example, a public-read, private-write property is expressed by:

public private(set) var item: SomeType

But there is no way, currently, to provide the opposite, e.g.

public private(**get**) var item: SomeType

This is really helpful for push-style input-only interfaces such as RxSwift's Relay/Subject, but it really is useful for any situation where you want to provide an input-style interface, in general.

As of today, if you want to provide a "input" for some object, such as "Let object X know that some value has changed", there is no way to prevent the writer to also read the value back.

In my experience it is a relatively common use case, but I'm really interested to hear other people's opinions on this.

Do you imagine this being useful to you, or part of Swift?

Thanks for reading :slight_smile: !

6 Likes

I'm not sure what the rest of the community thinks, but I can imagine that this is due to the fact that we only allow { get } or { get set } but not { set } only properties. I'm not sure how useful this would be because you can always make the whole property private and expose a public mutating func setItem(_ item: SomeType) function.

you can always make the whole property private and expose a public mutable func setItem(_ item: SomeType)` function.

I think you meant mutating, and you can only do this with Structs AFAIR, but even so, It's still not a perfect solution. I kinda wish there was a nicer way to express that need.

Thx, fixed. Well mutating was applied as an example, on classes you can omit it, but the the general idea remains the same. That said, I'm not against, but also not for the piched idea because I'm not sure if should be a thing in Swift. However I'm curious what the rest of the community thinks.

Indeed, semantically it's the same, but you cannot use the setter syntax value.item = item

1 Like

One scenario that I have encountered is where I want the getter to return a specific type, but the setter should accept any type conforming to a protocol.

For example, a Matrix might expose a column subscript, which returns a Matrix.Column instance, but you should be able to assign any S: Sequence where S.Element == Element to it.

3 Likes