- API fetch
- Array
- Async await
- Class
- Closures
- Computed property
- Concurrency
- Constants
- Data types
- Defer statement
- Dictionary
- Enum
- Escaping closure
- Extension
- For loop
- forEach
- Function
- Generics
- Guard statement
- if let statement
- Inheritance
- inout
- Lazy var
- Operator
- Optionals
- Property observers
- Property wrapper
- Protocol
- String formatting
- String interpolation
- Struct
- Switch statement
- Try catch
- Tuple
- Variables
- While loop
SWIFT
Swift Computed Properties: Syntax, Behavior, and Use Cases
Computed properties in Swift let you define a property whose value is calculated every time it’s accessed. Unlike stored properties, they don’t hold data in memory—instead, they use a getter (and optionally a setter) to compute their value on demand.
This approach is ideal when a property depends on other values or encapsulates logic you want to keep concise and readable. Computed properties work in structs, classes, and enums, helping you simplify code and ensure consistency across your types.
Declaring a Computed Property
The simplest form includes just a get
block:
struct Rectangle {
var width: Double
var height: Double
var area: Double {
return width * height
}
}
Here, area
is calculated dynamically whenever accessed:
let rect = Rectangle(width: 4, height: 5)
print(rect.area) // Output: 20.0
You access it just like a stored property, but there’s no underlying value—it’s recalculated each time.
Read-Only vs Read-Write
A computed property can also include a set
block to make it writable:
struct Temperature {
var celsius: Double
var fahrenheit: Double {
get {
return celsius * 9 / 5 + 32
}
set {
celsius = (newValue - 32) * 5 / 9
}
}
}
Now you can assign to fahrenheit
, and the internal celsius
value will update accordingly.
The newValue
Keyword
When defining a setter, Swift provides an implicit newValue
parameter representing the incoming value:
var score: Int {
get {
return internalScore
}
set(newScore) {
internalScore = max(0, newScore)
}
}
You can rename newValue
if needed, which is helpful when clarity matters in complex logic.
When to Use a Computed Property vs a Function
The choice between a computed property and a function depends on intent:
- Use a computed property when accessing a value that feels like a field—lightweight and derived from internal state.
- Use a function when computation needs parameters, involves side effects, or is performance-intensive.
// Property
var isLoggedIn: Bool {
return token != nil
}
// Function
func calculateDiscount(for price: Double) -> Double {
return price * 0.9
}
If you wouldn’t expect parentheses when accessing the value, a computed property is likely the better fit.
Computed Properties in Enums
Enums in Swift can contain computed properties too, which is helpful for adding derived information or descriptions:
enum Direction {
case north, south, east, west
var isVertical: Bool {
return self == .north || self == .south
}
}
Now:
let d = Direction.north
print(d.isVertical) // true
This enriches enums without needing to store extra state.
Usage in Classes and Inheritance
Computed properties can be overridden in subclasses, allowing custom behavior while keeping the same interface:
class Person {
var fullName: String {
return "Unknown"
}
}
class Employee: Person {
var firstName: String
var lastName: String
override var fullName: String {
return "\(firstName) \(lastName)"
}
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
}
This pattern lets subclasses tailor logic to their needs without duplicating APIs.
Lazy vs Computed
A lazy property stores its value and initializes it only once—when accessed for the first time. In contrast, a computed property recalculates its value every time you access it.
class Profile {
lazy var avatarImage: UIImage = {
return loadImageFromDisk()
}()
}
Use lazy properties for expensive, one-time setup. Use computed properties when the value must always reflect the current state.
Property Observers Compatibility
You can’t use willSet
or didSet
with computed properties, since there’s no underlying storage. If you need to react to changes, implement the behavior inside the set
block or elsewhere in your logic.
Best Practices
Follow these guidelines when using computed properties:
- Keep them fast: Avoid slow operations or I/O in the getter.
- No side effects in getters: They should only return values, not modify state.
- Use functions for complex logic: If something’s expensive or needs parameters, go with a method.
- Name thoughtfully: Use noun-like names that suggest a value, not an action.
Computed Properties in SwiftUI
In SwiftUI, computed properties can clean up your views by moving logic out of the body
block:
struct UserProfileView: View {
var user: User
var fullName: String {
"\(user.firstName) \(user.lastName)"
}
var body: some View {
Text(fullName)
}
}
This keeps the view declarative and makes state transformations easier to manage.
Advanced Use Cases
Computed properties are often used to:
- Format values (e.g., convert numbers to currency)
- Derive logic-driven UI state (
isButtonDisabled
) - Access underlying model properties with a custom interface
- Combine multiple stored values into one readable output
They also work well alongside @Published
, @State
, and other SwiftUI property wrappers, serving as derived values.
Summary
Computed properties in Swift give you a powerful way to define dynamic values without storing extra state. They behave like regular properties but run custom logic under the hood, making them ideal for clean, declarative code.
Used correctly, they can reduce duplication, clarify intent, and encapsulate logic within your types. Whether you’re working with structs, classes, or SwiftUI views, computed properties are a valuable part of the Swift language for building maintainable and expressive applications.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.