[swift-evolution] SE-0030 Property Behaviors

Taras Zakharko taras.zakharko at uzh.ch
Sun Feb 14 05:53:57 CST 2016


Ok, thanks for explaining, now I finally understand how this is supposed to work (thats what happens when one just skims through he proposal and missed important paragraphs). So in the end, it is magic that wraps the initialiser expression in a per-declaration closure. I’d rather such things be under full programmer control. Even more, what would happen in the following case?

public behavior var [custom] _: Value = initialValue {
  var value: Value = initialValue // alternatively init() { value = initialValue} 
  get
  {
   return value
  }
  set
  {
    value = newValue
  }
}

var global_x = 1

class Test {
 var [custom] x : Int = global_x + 1
}

let t1 = Test()
print(t1.x)
global_x = 2
let t2 = Test()
print(t2.x) // 2 or 3???


What gets printed in the last line? If I read the proposal correctly (but by now I expect to have missed something AGAIN in all honestly), the initialValue expression is gets wrapped in a computed property. This property is first accessed when the storage is initialised, i.e. when the host object instance is constructed. This means that t1 and t2 should get two different initial values which is probably not what one would have intended. Implicit wrapping of the initialiser is a good idea if we are interested in the lazy behaviour but it could be a source of bugs if we are *not*. 

— Taras


> On 14 Feb 2016, at 11:58, Brent Royal-Gordon <brent at architechies.com> wrote:
> 
>> Ah, yes, sorry, should have double checked with the initial text before sending the message. For some reason I though that the accessor requirement declarations were limited to get/set. But I think that my basic point still holds. E.g. in Joe’s proposal, I don’t really see how lazy behaviour is achieved: the sample implementation for lazy he proposes seems to force evaluation of the initial value at the declaration time. Unless we have some sort of magic that wraps the initial value into a closure (but that is then the same as what Anton suggests, albeit explicitly). 
> 
> In Joe's proposal, the initializer expression is wrapped up in a computed property. Because it's a *computed* property, rather than a *stored* property containing a closure, it doesn't take up any extra storage in the instances.
> 
> -- 
> Brent Royal-Gordon
> Architechies
> 



More information about the swift-evolution mailing list