Skip to content

Instantly share code, notes, and snippets.

@cSquirrel
Last active November 26, 2015 11:19
Show Gist options
  • Save cSquirrel/c100154b369042792c8e to your computer and use it in GitHub Desktop.
Save cSquirrel/c100154b369042792c8e to your computer and use it in GitHub Desktop.
/**
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