[swift-dev] Initializing constant object graph with cycles

Anton Mironov antonvmironov at gmail.com
Tue Nov 8 05:23:12 CST 2016


> On Nov 8, 2016, at 4:17 AM, Greg Parker <gparker at apple.com> wrote:
> 
>> 
>> On Nov 4, 2016, at 2:57 AM, Anton Mironov via swift-dev <swift-dev at swift.org <mailto:swift-dev at swift.org>> wrote:
>> 
>> Hi all,
>> 
>> I want to initialize constant object graph with cycles. I've considered two workarounds, but this is not a way I want it to be.
>> 
>> Here is an example:
>> ```
>> // I have a context
>> protocol Context : class {
>>  /* some */
>> }
>> 
>> // I have an object that has sense only in context
>> class ObjectInContext {
>>  private weak var context: Context?
>> 
>>  init(context: Context) {
>>    self.context = context
>>  }
>> }
>> 
>> // This is what I want to do
>> // The object graph has a cycle, but there is no a retain cycle
>> class ContextA : Context {
>>  let object: ObjectInContext
>> 
>>  init() {
>>    self.object = ObjectInContext(context: self) // this code will not compile for many good reasons
>>  }
>> }
>> 
>> // 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)
>>  }
>> }
> 
> The IUO is the typical pattern here. 
> 
> Forgetting to initialize an IUO is less of a problem than it would be in C or ObjC. Access to an IUO is checked at runtime. If you forget to initialize self.object then the process will deliberately halt the first time you try to use it.
> 
> 
> -- 
> Greg Parker     gparker at apple.com <mailto:gparker at apple.com>     Runtime Wrangler

I agree that IUO is the best solution for now.
Sometimes I search though Scala to find the best way of doing things. They've came up with lazy as the best practice for such cases.

I’ve found (SR-1042 Make "lazy var" threadsafe)[https://bugs.swift.org/browse/SR-1042]. Implementing this will help. But I am not sure if it will be implemented any time soon.

Thanks,
Anton Mironov

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-dev/attachments/20161108/8718f8d7/attachment.html>


More information about the swift-dev mailing list