Last active
November 26, 2015 11:19
-
-
Save cSquirrel/c100154b369042792c8e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Problem | |
*/ | |
class Parent { | |
var children:Array<String> | |
init() { | |
self.children = discoverChildren() // <-- error: method call 'discoverChildren' before all store properties are initialized | |
} | |
func discoverChildren() -> Array<String> { | |
return ["a","b","c","d","e"] | |
} | |
} | |
/** | |
Solution #1 | |
*/ | |
class Parent1 { | |
var children:Array<String> | |
init() { | |
// shut up the compiler with dummy value | |
self.children = Array<String>() | |
// now can call the method to provide real value | |
self.children = discoverChildren() | |
} | |
func discoverChildren() -> Array<String> { | |
return ["a","b","c","d","e"] | |
} | |
} | |
/** | |
Solution #2 | |
*/ | |
class Parent2 { | |
// 'lazy' allows self reference | |
lazy var children:Array<String> = { | |
return self.discoverChildren() | |
}() | |
init() { | |
} | |
func discoverChildren() -> Array<String> { | |
return ["a","b","c","d","e"] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment