initialization - How to initialize bidirectional graph in Swift? -
i have classes create graph "back pointers". tried make pointers unowned (they'd create cycles otherwise) , initialize them in init(), creates problems self references. how supposed around this?
class parent { var child1:child var child2:child unowned var myowner:thing init(myowner:thing) { child1 = child(parent: self) // compiler errors here child2 = child(parent: self) // , here self.myowner = myowner } } class child { unowned var parent:parent init(parent:parent) { self.parent = parent } } the error is
'self' used before all stored properties initialized
you have error because swift enforces variables must have value before can use self avoid instance not being initialised. in case have 2 options:
1. mark child1 , child2 implicitly unwrapped optionals:
class parent { var child1: child! var child2: child! unowned var myowner:thing init(myowner:thing) { // note - myowner being set before children. self.myowner = myowner child1 = child(parent: self) child2 = child(parent: self) } } this results in no errors because both child1 , child2 have default value of nil, changing in init.
2. use lazy instantiation:
class parent { lazy var child1: child = child(parent: self) lazy var child2: child = child(parent: self) unowned var myowner:thing init(myowner:thing) { self.myowner = myowner } } this results in no errors because lazy property's value calculated when first used, therefore self guaranteed have been initialised.
hope helps.
Comments
Post a Comment