[swift-evolution] Support for pure setters

David James davidbjames1 at gmail.com
Thu Jan 7 09:47:20 CST 2016

Currently Swift has computed properties that support get or get and set, but not set only. There are use cases where we would want set only. 

For example, toggling a boolean which changes another stored property where it would be overkill to make a method for that. It's more intuitive to just assign a boolean. e.g. myObject.myBoolean = true

Another example, setting an object that is introspected in order to create a new object which is then stored on a different property. The property that is stored could be readonly/get, for example. A method for the setter (e.g. setSomething) would not be as intuitive as just a plain assignment (e.g. myObject.something = ..). 

Another consideration is that a pure setter would support better information hiding. You may not want the parent object to expose the property. Example scenario: set a property on an object (via assignment), which creates/modifies a stored property based on the passed (set) value, and then pass the parent object to another part of the system which can than read the stored property but not the original set property — i.e. you may not want to expose the original set property to another part of the system.


var myProperty:MyClass {
    set {

One concern is that without ‘get’ there really is no property at all, and perhaps this is the reason that pure setter was never included. However, this does not invalidate the above.

As an alternative (to make it more semantically sensible) we could introduce a new keyword ‘set’, so:

set myProperty:MyClass {

Which would support simple assignment:

myObject.myProperty = myOtherObject

Finally, it’s important to know that this is still “computed", but only computed on the input, not on the output side.

David James

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160107/69da380b/attachment.html>

More information about the swift-evolution mailing list