- 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 Property: Syntax, Behavior, and Use Cases
The Swift computed property
feature allows you to define a property whose value is calculated each time it's accessed, rather than being stored directly in memory. Unlike stored properties, a computed property doesn't hold data but instead provides a getter (and optionally a setter) to compute its value on demand.
Using computed property Swift
code is ideal when the value of a property depends on other values or when you want to encapsulate logic in a concise, readable way. Computed properties can be used in classes, structs, and enums to simplify code, improve clarity, and maintain consistency across property access.
Declaring a Computed Property in Swift
A basic Swift computed property
includes a get
block and optionally a set
block.
struct Rectangle {
var width: Double
var height: Double
var area: Double {
return width * height
}
}
In this example, area
is a computed property. It doesn't store a value—instead, it calculates the area using the current values of width
and height
.
You access it just like any other property:
let rect = Rectangle(width: 4, height: 5)
print(rect.area) // Output: 20.0
Read-Only vs Read-Write Computed Properties
A read-only computed property has only a get
block. However, you can also define a computed property with both get
and set
blocks to allow assignment.
struct Temperature {
var celsius: Double
var fahrenheit: Double {
get {
return celsius * 9 / 5 + 32
}
set {
celsius = (newValue - 32) * 5 / 9
}
}
}
Now you can get and set fahrenheit
, and it updates the internal celsius
value accordingly.
The newValue
Keyword
In the setter block of a computed property, Swift provides an implicit newValue
parameter representing the value being assigned. You can also rename this parameter if needed:
var score: Int {
get {
return internalScore
}
set(newScore) {
internalScore = max(0, newScore)
}
}
This level of control makes computed property Swift
patterns both flexible and expressive.
Computed Property vs Function in Swift
A common question is the difference between computed property vs function Swift
.
- Use a computed property when the value feels like a property (i.e., it's cheap to compute and behaves like a field).
- Use a function when the computation involves side effects, requires parameters, or is expensive.
For example:
// Computed property
var isLoggedIn: Bool {
return token != nil
}
// Function
func calculateDiscount(for price: Double) -> Double {
return price * 0.9
}
The isLoggedIn
property feels like a property because it reflects a simple condition about the current state. On the other hand, calculateDiscount
requires an input and performs a transformation, so it’s better modeled as a function.
Using Computed Properties in Enums
Swift allows computed properties inside enums, which is useful for creating human-readable descriptions or derived values.
enum Direction {
case north, south, east, west
var isVertical: Bool {
return self == .north || self == .south
}
}
Now you can write:
let d = Direction.north
print(d.isVertical) // true
This kind of pattern adds powerful expressiveness to enumerations without storing additional state.
Computed Properties in Classes
When used in classes, a Swift computed property
can override stored or computed properties from a superclass:
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 is useful for customizing logic based on subclass-specific data while retaining a consistent interface.
Lazy vs Computed Properties
Another common point of confusion is the difference between lazy and computed properties.
- A lazy property stores its value and calculates it only once when first accessed.
- A computed property recalculates its value every time you access it.
Example of a lazy property:
class Profile {
lazy var avatarImage: UIImage = {
return loadImageFromDisk()
}()
}
Use lazy properties for expensive operations you don’t want to repeat, and computed properties when you want real-time, updated values based on current state.
Computed Properties and Property Observers
You can’t attach willSet
or didSet
observers to computed properties since they don’t actually store a value. Those observers only work with stored properties. If you need to respond to changes in a computed value, you’ll need to handle that logic manually—perhaps using a custom setter or triggering side effects from elsewhere.
Best Practices for Computed Properties
- Keep them lightweight: A computed property should ideally be quick to evaluate and side-effect free.
- Avoid expensive calculations: If the property performs heavy operations or I/O, consider using a function or a lazy property instead.
- Avoid side effects: Don't include logic in a getter that changes state.
- Name clearly: Property names should reflect that you're accessing a value, not performing an action. Use verbs in functions, nouns in properties.
Computed Properties in SwiftUI
In SwiftUI, computed properties can help simplify view state or formatting:
struct UserProfileView: View {
var user: User
var fullName: String {
"\(user.firstName) \(user.lastName)"
}
var body: some View {
Text(fullName)
}
}
This makes the body
cleaner and avoids repeating logic.
Advanced Use Cases
You can also use computed properties to:
- Format data (e.g., format a number as a currency string).
- Combine multiple properties (e.g., concatenate names).
- Derive UI state (e.g.,
isButtonDisabled
). - Proxy access to underlying data models.
Computed properties are often used in conjunction with property wrappers like @Published
or @State
, where they act as derived values.
Summary
The Swift computed property
syntax is a powerful feature that enables dynamic value computation within your types. A computed property in Swift provides a clean, declarative way to encapsulate logic that transforms or combines values, all while maintaining a natural property-like access pattern.
Using computed property Swift
code correctly allows you to avoid redundancy, improve maintainability, and create expressive APIs. Unlike functions, computed properties don’t require parameters and feel more like natural parts of an object or struct. Understanding their behavior and best practices will help you write more concise and idiomatic Swift code, especially in combination with enums, structs, and SwiftUI views.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.