Swift iOS tips
- qmshahzad
- Feb 5, 2025
- 1 min read
Swift iOS Tip: Use lazy var for Expensive Initializations
If a property requires complex setup or depends on other properties, use lazy var to delay its initialization until it's first accessed. This improves performance and avoids unnecessary computations when the property is not needed.
Example Without lazy var (Unnecessary Work on Initialization)
class MyViewController: UIViewController { let formattedDate: String = { let formatter = DateFormatter() formatter.dateStyle = .medium return formatter.string(from: Date()) }()
override func viewDidLoad() { super.viewDidLoad() print(formattedDate) }}
In this case, formattedDate is initialized even if we never use it.
Using lazy var (Optimized Initialization)
class MyViewController: UIViewController { lazy var formattedDate: String = { let formatter = DateFormatter() formatter.dateStyle = .medium return formatter.string(from: Date()) }()
override func viewDidLoad() { super.viewDidLoad() print(formattedDate) // Initialized only when accessed }}
Why It Matters?
Performance Optimization: Avoids unnecessary work during initialization.
Efficient Memory Usage: Object is created only when needed.
Better Dependency Handling: If the property depends on self, lazy var ensures it's initialized after self is fully available.
Here are some hashtags for your Swift iOS tip:
General Swift Development Hashtags:
Comments