Design Converter
Education
Last updated on Jan 20, 2025
Last updated on Dec 20, 2024
Software Development Executive - II
One of the key concepts in Swift programming is the computed property, which is a type of property used to encapsulate logic for dynamically calculating a value instead of directly storing it.
This blog delves deep into computed variables in Swift, explains the mechanics of computed properties and stored properties, and demonstrates how these tools can enhance your programming experience.
Let’s make your coding life easier! 🚀
In Swift, properties associate values with instances of a class, structure, or enumeration. Properties are divided into two types:
Stored properties: These directly store values within a class or structure.
Computed properties: These dynamically compute their value using custom logic rather than storing it directly.
Here’s how they differ in functionality:
A stored property is the simplest kind of property. A stored property holds a default or assigned value directly in the memory associated with an instance.
1struct Person { 2 var firstName: String 3 var lastName: String 4 var age: Int 5} 6 7let person = Person(firstName: "John", lastName: "Doe", age: 30) 8print(person.firstName) // Outputs: John
In this example, firstName
, lastName
, and age
are stored properties. They store values directly for each new instance of the Person
structure.
A computed property differs from a stored property because it doesn’t directly store a value. Instead, it provides a getter to calculate and return a value, and optionally includes a setter to modify related properties.
A computed property is defined using the var
keyword and a getter block. Optionally, it can include a setter block for updating other values.
1struct Circle { 2 var radius: Double 3 var circumference: Double { 4 get { 5 return 2 * .pi * radius 6 } 7 set(newCircumference) { 8 radius = newCircumference / (2 * .pi) 9 } 10 } 11} 12 13var circle = Circle(radius: 5) 14print(circle.circumference) // Outputs: 31.415 15circle.circumference = 62.83 16print(circle.radius) // Updates radius based on the new value assigned to circumference
Here:
circumference
is a computed property.If you only need a read-only computed property, you can omit the set
block.
1struct Square { 2 var sideLength: Double 3 var area: Double { 4 return sideLength * sideLength 5 } 6} 7 8let square = Square(sideLength: 4) 9print(square.area) // Outputs: 16
The area
is a read-only computed property because it lacks a set
block.
Often, stored and computed properties coexist in the same class or structure, enabling developers to manage data flexibly. You might have a stored property for input values and a computed property to derive a new result.
1struct Person { 2 var firstName: String 3 var lastName: String 4 var fullName: String { 5 return "\(firstName) \(lastName)" 6 } 7} 8 9let person = Person(firstName: "Jane", lastName: "Doe") 10print(person.fullName) // Outputs: Jane Doe
Here, fullName
is a computed property that derives its value from the firstName
and lastName
stored properties.
A read-only computed property doesn’t have a setter. It’s ideal for scenarios where you only need to retrieve a derived value without modifying other properties.
Example:
1struct Rectangle { 2 var width: Double 3 var height: Double 4 var area: Double { 5 return width * height 6 } 7}
In Swift, a computed property can optionally include a get
keyword to define its logic explicitly. This allows for precise control over how the property calculates and returns values.
Property observers, such as willSet
and didSet
, track value changes in stored properties. They don’t apply to computed properties since these don’t directly store values.
Example:
1struct Counter { 2 var count: Int = 0 { 3 willSet { 4 print("About to set count to \(newValue)") 5 } 6 didSet { 7 print("Count changed from \(oldValue) to \(count)") 8 } 9 } 10} 11 12var counter = Counter() 13counter.count = 10 14// Outputs: 15// About to set count to 10 16// Count changed from 0 to 10
Here’s an example demonstrating a filename property that combines a stored property with a computed property:
1struct File { 2 var name: String 3 var extensionType: String 4 var filename: String { 5 return "\(name).\(extensionType)" 6 } 7} 8 9let file = File(name: "document", extensionType: "txt") 10print(file.filename) // Outputs: document.txt
Understanding a computed variable in Swift can simplify your coding process and improve readability. Comparing how Kotlin and Golang approach similar concepts helps you pick the best tools for your projects. Keep practicing, experimenting, and building amazing 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.