[swift-dev] Initializing constant object graph with cycles

Anton Mironov antonvmironov at gmail.com
Fri Nov 4 04:57:57 CDT 2016


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)
  }
}

// This is workaround #2
// It looks bad because it is even easier to forget to initialize object in init
class ContextC : Context {
  lazy var object: ObjectInContext = ObjectInContext(context: self)
  
  init() {
    let _ = self.object // lazy is not atomic so I rather initialize it here
  }
}
```

Does anyone have any ideas how can I do this without workarounds?

Thanks,
Anton Mironov


More information about the swift-dev mailing list