If you’ve been writing Swift for a while, you’ve probably bumped into computed properties. They’re one of those language features that seem deceptively simple at first, but the more you use them, the more you realize how elegant (and powerful) they can be.
Let’s break them down—no jargon overload, just clean explanations with some real-world Swift vibes.
In Swift, a property is basically a value associated with a class, struct, or enum. Normally, you’d think of properties as just stored values, like:
struct User {
var name: String
var age: Int
}
But sometimes, you don’t want to just store a value—you want to calculate it on demand. That’s where computed properties come in.
A computed property doesn’t hold data itself. Instead, it defines a getter (and optionally a setter) to return or update a value dynamically.
Here’s the syntax:
struct Rectangle {
var width: Double
var height: Double
var area: Double {
return width * height
}
}
Notice that area
isn’t stored anywhere—it’s calculated each time you access it.
rectangle.width * rectangle.height
everywhere, you use rectangle.area
.By default, a computed property is read-only if you just implement get
.
struct Circle {
var radius: Double
var diameter: Double {
get {
return radius * 2
}
}
}