Junior — Middle
Can you explain the principle of lazy loading?
sobes.tech AI
Answer from AI
Lazy loading is a technique where an object or resource is loaded or initialized only at the moment of first access, rather than at application startup or creation. This helps save resources and speeds up startup.
In iOS, lazy loading is often implemented using the lazy property in Swift:
class DataManager {
lazy var data: [String] = {
print("Loading data...")
return ["Item1", "Item2", "Item3"]
}()
}
let manager = DataManager()
// Data is not loaded until data is accessed
print(manager.data) // Loading occurs here and output is shown
In this example, the data array is created only upon first access, saving time and memory if the data might not be needed immediately.