Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Lazy Initialization in Swift
Written by Team Kodeco

Lazy Initialization is a design pattern used in Swift to defer the creation of an object until it’s needed. This means that an object is only created when it’s first accessed, and not before. This can be useful for optimizing performance and managing the memory of your objects.

Here is an example of using Lazy Initialization in Swift:

class Lightsaber {
  var color: String
  init(color: String) {
    self.color = color
    print("Lightsaber initialized")
  }
  deinit {
    print("Lightsaber \(color) is being deactivated")
  }
}

class Jedi {
  lazy var lightsaber: Lightsaber = {
    return Lightsaber(color: "blue")
  }()
  deinit {
    print("Jedi is leaving the order")
  }
}

var jediKnight: Jedi? = Jedi()
print("Jedi Created")
print("Accessing lightsaber for first time...")
let lightSaberColor = jediKnight!.lightsaber.color
jediKnight = nil
// Output: Jedi Created
//         Accessing lightsaber for first time...
//         Lightsaber initialized
//         Jedi is leaving the order
//         Lightsaber blue is being deactivated

In this example, a Jedi class has a property called lightsaber which is marked as lazy. This means that the lightsaber object won’t be created until it’s accessed for the first time. When the Jedi object is first created, the “Lightsaber initialized” message isn’t printed because the lightsaber object hasn’t been accessed yet.

When the lightsaber’s color property is accessed for the first time, the lazy variable’s closure is executed and the lightsaber object is created and the “Lightsaber initialized” message is printed.

When the jediKnight variable is set to nil, there are no longer any references to the Jedi object so it’s deallocated. At that point, there are no more references to the Lightsaber object, so it’s deallocated as well.

By using lazy initialization like in this example, you can avoid creating unnecessary objects until they are actually needed, which can help improve performance and memory management in your application.

© 2024 Kodeco Inc.