[swift-users] [swift-dev] Initializing constant object graph with cycles

Brent Royal-Gordon brent at architechies.com
Fri Nov 4 06:35:20 CDT 2016


(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-dev at 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



More information about the swift-users mailing list