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