Instantly share code, notes, and snippets.

Embed
What would you like to do?
Using an auto-executing closure to initialize a lazy stored property
class SomeClass {
lazy var fibonacciNumbers: [Int] = {
var fibonacciNumbers = [0, 1, 1]
for index in 2...8 {
let currentNum = fibonacciNumbers[index]
let prevNum = fibonacciNumbers[index - 1]
let newNum = currentNum + prevNum
fibonacciNumbers.append(newNum)
}
return fibonacciNumbers
}()
func addOneMoreFibonacciNumber() {
let currentNum = fibonacciNumbers.last!
let prevNum = fibonacciNumbers[fibonacciNumbers.count - 2]
let newNum = currentNum + prevNum
fibonacciNumbers.append(newNum)
}
}
let instance = SomeClass()
instance.addOneMoreFibonacciNumber()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment