1. Introduction
In Swift, a lazy stored property is a property whose initial value isn't calculated until the first time it's accessed. This can be useful when the initial value for a property is dependent on external factors or when the initial value requires complex computation. The lazy keyword is used before the property declaration to indicate a lazy stored property.
2. Source Code Example
// Define a class to demonstrate lazy properties
class DataFetcher {
// Simulating a heavy data-fetching operation
func fetchData() -> String {
print("Fetching data...")
return "Sample Data"
}
}
class DataManager {
lazy var data: String = dataFetcher.fetchData()
let dataFetcher = DataFetcher()
}
// Create an instance of DataManager
let manager = DataManager()
// No output is seen yet since the lazy property hasn't been accessed
// Access the lazy property
print(manager.data)
Output:
Fetching data... Sample Data
3. Step By Step Explanation
1. Setting Up:
- A class DataFetcher is created to simulate a data-fetching operation that is computationally heavy or time-consuming. The fetchData method prints "Fetching data..." when it's called.
- A DataManager class contains a lazy stored property data that calls the fetchData method of DataFetcher.
2. Lazy Behavior in Action:
- An instance of DataManager is created, but you'll notice no output is printed yet. This is because the lazy property data hasn't been accessed and therefore the fetchData method hasn't been called.
- Once we access the data property with print(manager.data), the fetchData method is called, and "Fetching data..." is printed, followed by "Sample Data".
Using lazy is beneficial when initializing a property involves a lot of resources, and it's not certain if the property will be used. It ensures that the computation is deferred until it's truly necessary.
Comments
Post a Comment