(Crossposted to swift-users; swift-dev is for development of the Swift compiler 
and standard library, not discussions about how to use Swift.)

> On Nov 4, 2016, at 2:57 AM, Anton Mironov via swift-dev <swift-...@swift.org> 
> wrote:
> 
> // This is workaround #1
> // It looks bad for 2 reasons: implicitly unwrapped optional, it is easy to 
> forget to initialize object
> class ContextB : Context {
>  var object: ObjectInContext!
> 
>  init() {
>    self.object = ObjectInContext(context: self)
>  }
> }

Try this:

        class ContextB: Context {
                private var _object: ObjectInContext?
                var object: ObjectInContext { return _object! }
                
                init() {
                        _object = nil
                        // Note that self is now fully initialized
                        _object = ObjectInContext(context: self)
                }
        }

As long as you can trust yourself not to forget to initialize `_object` within 
`init()` or mutate `_object` within private scope, this is about as safe as 
anything you could hope for.

-- 
Brent Royal-Gordon
Architechies

_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users

Reply via email to