> On Nov 4, 2016, at 2:57 AM, Anton Mironov via swift-dev <swift-dev@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 gpar...@apple.com <mailto:gpar...@apple.com> Runtime Wrangler
_______________________________________________ swift-dev mailing list swift-dev@swift.org https://lists.swift.org/mailman/listinfo/swift-dev