[swift-dev] Initializing constant object graph with cycles

Greg Parker gparker at apple.com
Mon Nov 7 20:17:25 CST 2016


> On Nov 4, 2016, at 2:57 AM, Anton Mironov via swift-dev <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


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-dev/attachments/20161107/22a5096e/attachment.html>


More information about the swift-dev mailing list