Lazy Initialization in Swift
Written by Team Kodeco
In Swift, you can use lazy initialization to delay the initialization of a variable or constant until it is first used. This can be useful in situations where the initial value of a variable or constant is computationally expensive to create or is not immediately required.
For example, to use lazy initialization to delay the initialization of an array, you can use the following syntax:
lazy var expensiveArray = {
// Expensive computation to create array
return [Int]()
}()
In this example, expensiveArray
is a variable that is only initialized when it’s first accessed, rather than when the containing class or struct is initialized.
You can also use lazy initialization with properties that have a getter and setter:
lazy var exampleString: String = {
// expensive or time-consuming initialization
return "Hello, world!"
}()
var exampleStringValue: String {
get {
return exampleString
}
set {
exampleString = newValue
}
}
Example in Context
Here’s an example of this in the context of a class:
class TestClass {
lazy var expensiveArray = {
// Expensive computation to create array
print("Accessed here!")
return [Int]()
}()
func test() {
print("Starting test")
print(expensiveArray)
print("Ending test")
}
}
var test = TestClass()
test.test()
If you run this, you’ll get the following output:
Starting test
Accessed here!
[]
Ending test