[swift-evolution] Fwd: [Proposal] Property behaviors

Matthew Johnson musical.matthew at mac.com
Wed Jan 20 11:31:23 CST 2016


I’m wondering if you missed my comments.  I had a few questions I haven’t seen answered yet so I’m bumping them. 


The proposal makes it clear when an initializer is required but is a little bit less clear about when it may be left off.  Is this correct?

var [baseProp] x // no initializer, ok as long as base doesn't have init req?
var [initializerReqt] y // no initializer, error because of the initializer requirement?

Another thing that isn’t clear is what happens when a property with a behavior is set within the initializer of the containing type:

struct S {
  var [observed] s: String
  init(s: String) {
    // What happens here?  Is the behavior’s “set” accessor called?  
    // This may not always be desirable, as in the case of “observed"
    self.s = s

One thought is that it might be good to allow behaviors to have `init` accessor that is used if the property is assigned by an initializer of the containing type (only the first time the property is assigned).  This would clarify what happens during initialization of the containing type and allow for different init and set code paths when necessary.   It would be distinguished from the behavior initializer by the lack of parens.  If that is too subtle we could use a different name for the initialization accessor.

This would also allow us to support a variant `delayedImmutable` that *must* be assigned during initialization of the containing type, but not necessarily during phase 1.  That behavior would facilitate maximum safety when we must pass `self` to the initializer when constructing an instance to assign to a property (not an uncommon use case).  

If the compiler could enforce slightly relaxed initialization rules that require initialization of the property before the initializer exits and before the property is read in the initializer body, but not necessarily during phase 1, then we could achieve nearly complete static safety.  The only window for error would be any uses of self that happen outside the initializer body before the property is initialized.  

The behavior might look like this:

public var behavior phase2Immutable<Value>: Value {
  private var value: Value? = nil

  get {
    guard let value = value else {
      fatalError("property accessed before being initialized")
    return value
  init {
    value = initialValue

This would be a significant improvement over delayedImmutable in many use cases IMO.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160120/62a831bb/attachment.html>

More information about the swift-evolution mailing list