[swift-evolution] [Pitch] mutable `newValue` in willSet

Karl razielim at gmail.com
Sun Sep 11 22:50:34 CDT 2016


Sometimes you would like to modify the value being set to a property before it is set.

Currently, you would have to add a separate backing property and implement the getter and setter, even if you want to perform a simple bounds-check on the value being set and want to cap it to allowed values.

e.g:

var bounds : Bounds {
    willSet {
      // Cap the bounds
      newValue = newValue.capped(to: maximumSize)
      // Some comments to demonstrate noise if we were doing more processing
      // Some comments to demonstrate noise if we were doing more processing
      // Some comments to demonstrate noise if we were doing more processing
    }

    didSet {
      // Load the new bounds
      // Some comments to demonstrate noise if we were doing more processing
      // Some comments to demonstrate noise if we were doing more processing
      // Some comments to demonstrate noise if we were doing more processing
    }
}

Against the workaround you have to do currently:

var _bounds : Bounds
var bounds : Bounds {
    get { return _bounds }
    set {
      // Cap the bounds
      _bounds = newValue.capped(to: maximumSize)
      // Some comments to demonstrate noise if we were doing more processing
      // Some comments to demonstrate noise if we were doing more processing
      // Some comments to demonstrate noise if we were doing more processing

      // Load the new bounds
      // Some comments to demonstrate noise if we were doing more processing
      // Some comments to demonstrate noise if we were doing more processing
      // Some comments to demonstrate noise if we were doing more processing
    }
}

Currently, the capping in willSet is a compile-time error because `newValue` is a let constant, but I find that breaking your accessor code up in to willSet/didSet blocks allows for greater readability, especially when you have lots of processing to do (in the workaround example, the validation/preprocessing code and effects/postprocessing code are only separated by a comment). I propose that, at least for the scope of willSet (and *not* didSet, if we can manage that), that the variable should be mutable.

Any thoughts?

Karl




More information about the swift-evolution mailing list