Member-only story
Lazy and Computed Property
6 min readJan 23, 2025
What is the problem with the below code?
class Person {
var firstName: String {
"niraj"
}
var lastName: String = {
"paul"
}()
}
Problems
class Person {
// Computed property
var firstName: String {
"niraj" // A computed property that always returns "niraj"
}
// Lazy property (incorrect syntax!)
var lastName: String = {
"niraj" // This is not valid for a lazy property
}()
}
Solutions
class Person {
// Computed property
var firstName: String {
"niraj"
}
// Lazy property
lazy var lastName: String = {
"niraj" // A closure that initializes the property when accessed
}()
}
Explanation:-
firstName
- Computed Property
- The
firstName
property is a computed property. - Every time you access it, it evaluates the block of code in
{}
and returns"niraj"
. - No stored value; it only returns the value dynamically.
lastName
as Lazy Property:
- The
lastName
property is initialized only the first time it is accessed. - After initialization, it stores the value
"niraj"
for future use.