Education
Software Development Executive - III
Last updated onDec 20, 2024
Last updated onDec 20, 2024
Swift's stored properties are a fundamental aspect of managing data within classes and structures. Enumerations can store data indirectly using associated values.
Understanding the differences between stored and computed properties, alongside concepts like lazy stored properties, property observers, and type properties, is crucial for writing efficient and clean code.
This blog explores the nuances of stored properties, their initialization, behavior, and how they interact with computed properties to help you master property management in Swift. Let’s dive in!
A stored property is a variable or constant that is part of an instance of a class, structure, or enumeration. Stored properties hold a value for as long as the instance exists in memory, determined by its scope and references. Swift allows you to define these properties with an initial value, or you can assign a default value directly in their declaration.
Swift
1struct Rectangle { 2 var width: Double 3 var height: Double 4} 5 6var rect = Rectangle(width: 10.0, height: 20.0) 7print("Rectangle Width: \(rect.width), Height: \(rect.height)")
In the above example, width and height are stored properties. They store constant and variable values for each instance of the Rectangle structure.
Stored properties can be categorized based on their behavior and initialization.
A variable stored property is declared using the var keyword and allows modification after initialization. For example:
Swift
1class Person { 2 var name: String 3 var age: Int 4 init(name: String, age: Int) { 5 self.name = name 6 self.age = age 7 } 8} 9 10var person = Person(name: "Alice", age: 30) 11person.age = 31 12print("Updated age: \(person.age)")
A constant stored property is declared using the let keyword. Once set, its value cannot be changed. Constant stored properties are especially useful when defining values that should remain immutable throughout the instance's lifecycle.
Swift
1struct FixedPoint { 2 let x: Int 3 let y: Int 4} 5 6let point = FixedPoint(x: 10, y: 20) 7// point.x = 30 // This will throw an error
A lazy stored property is initialized only when it is first accessed, which delays memory allocation and computational overhead until required. This is especially useful for properties that rely on expensive operations or external factors.
Swift
1class DataLoader { 2 lazy var data: String = { 3 // Simulate data loading 4 return "Loaded Data" 5 }() 6} 7 8let loader = DataLoader() 9print(loader.data) // "Loaded Data"
Lazy stored properties are defined using the lazy keyword and can only be var, as they need to be mutable.
While stored properties allocate memory for their values, computed properties do not. Instead, they calculate and return a value dynamically. Computed properties are defined with a getter and, optionally, a setter.
Swift
1struct Circle { 2 var radius: Double 3 var diameter: Double { 4 get { 5 return radius * 2 6 } 7 set { 8 radius = newValue / 2 9 } 10 } 11} 12 13var circle = Circle(radius: 5) 14print(circle.diameter) // 10 15circle.diameter = 12 16print(circle.radius) // 6
The setter allows us to update the radius indirectly by assigning a new value to the diameter.
If a computed property only has a getter, it is considered a read-only computed property. These properties do not allow setting a new value.
Swift
1struct Square { 2 var side: Double 3 var area: Double { 4 return side * side 5 } 6}
Property observers let you monitor and respond to changes in a property's value. They are supported only by stored properties and can be implemented using willSet and didSet.
Swift
1class Counter { 2 var count: Int = 0 { 3 willSet { 4 print("Count is about to change to \(newValue)") 5 } 6 didSet { 7 print("Count has changed from \(oldValue) to \(count)") 8 } 9 } 10} 11 12let counter = Counter() 13counter.count = 10 14counter.count = 15
In this example, the count property has observers that react whenever its value changes.
One of the benefits of using a lazy stored property is optimizing memory usage. This type of property delays its initialization until it's explicitly accessed, which can help avoid unnecessary memory allocation.
Swift
1class ImageProcessor { 2 lazy var processedImage: String = { 3 // Simulated image processing 4 return "Processed Image" 5 }() 6}
Stored properties allocate memory because they need to retain their stored property's value. This makes them ideal for holding values that don't require dynamic recalculation, unlike computed properties.
Stored properties can also be used in combination with type properties. Type properties, defined using the static keyword, are associated with the type itself rather than any particular instance.
Swift
1struct Configuration { 2 static let maxConnections = 10 3 static var currentConnections = 0 4}
Here, maxConnections is a static constant, meaning its value cannot be changed and is shared across all instances.
You can use both stored and computed properties together in the same structure or class to balance memory usage and computation efficiency.
Swift
1struct Rectangle { 2 var width: Double 3 var height: Double 4 var area: Double { 5 return width * height 6 } 7}
In this example, width and height are stored properties, while area is a computed property.
The Swift stored property is a cornerstone of data handling in Swift. By understanding the differences between stored and computed properties, lazy stored properties, and type properties, you can write more efficient and readable code. Use stored properties to store values that need persistent memory, while leveraging computed properties to calculate values on the fly.
By combining the right mix of stored and computed properties, you can strike a balance between performance and simplicity in your code.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.