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

Anton Mironov antonvmironov at gmail.com
Fri Nov 4 08:14:19 CDT 2016


This workaround looks better, but it is still workaround.
I can trust myself this month and month after that. But I will look at this code after a while (or someone else will look at it) and will not remember/know that there has to be some initializations.
I am building tools that handle some common cases of synchronization and etc. These tools must be robust and beautiful so I can advice anyone to use them. None will adopt these tools if they introduce some new points of failure.


> On Nov 4, 2016, at 1:35 PM, Brent Royal-Gordon <brent at architechies.com> wrote:
> 
> (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