Blog / July 2, 2023 / 3 mins read / By Mahi Garg

Computed Property in Swift

In Swift, computed properties are a powerful and elegant feature that allows developers to define custom accessors for their properties. Unlike stored properties, computed properties do not store a value directly. Instead, they calculate their value on-the-fly based on the getter and, if needed, the setter logic provided by the developer. This flexibility opens up numerous possibilities for streamlining code, encapsulating complex logic, and creating more readable and maintainable code.

In this blog, we’ll dive into computed properties in Swift, learn how they work, and explore several real-world examples where they can significantly improve your code.

Simple Computed Property

Let’s start with a straightforward example. Imagine a Circle struct representing a circle with a given radius. Instead of manually computing the area each time, we can create a computed property area that automatically calculates it for us.

struct Circle {
    let radius: Double

    var area: Double {
        return Double.pi * radius * radius
    }
}

let circle = Circle(radius: 5)
print("Circle's area: \(circle.area)")

Computed Property with Dependencies

Computed properties can have dependencies on other properties within the same struct or class. For instance, consider a Rectangle struct with width and height properties. We can create a computed property perimeter that depends on these values.

struct Rectangle {
    var width: Double
    var height: Double

    var perimeter: Double {
        return 2 * (width + height)
    }
}

var rectangle = Rectangle(width: 10, height: 5)
print("Rectangle's perimeter: \(rectangle.perimeter)")

Read-Only Computed Property

Computed properties can be either read-only (with only a getter) or read-write (with both a getter and a setter). Let’s take a look at an example of a read-only computed property in the context of a Temperature struct.

struct Temperature {
    var celsius: Double

    var fahrenheit: Double {
        return celsius * 9 / 5 + 32
    }
}

let temperature = Temperature(celsius: 25)
print("Temperature in Fahrenheit: \(temperature.fahrenheit)")

Computed Property in Enums

Even enums can benefit from computed properties. Consider a Card enum representing a playing card. We can create a computed property isFaceCard that returns true for face cards (Jacks, Queens, and Kings).

enum Card {
    case ace, number(Int), face(String)

    var isFaceCard: Bool {
        switch self {
        case .face, .ace: return true
        case .number: return false
        }
    }
}

let card1 = Card.ace
let card2 = Card.face("Queen")

print("Card 1 is a face card: \(card1.isFaceCard)")
print("Card 2 is a face card: \(card2.isFaceCard)")

Conclusion

Computed properties in Swift offer a flexible and efficient way to encapsulate logic and simplify code. Whether you need to calculate derived properties, create dependencies between properties, or add custom behavior to your data structures, computed properties are the ideal tool for the job.

By embracing computed properties in your Swift code, you can enhance code readability, maintainability, and reduce redundancy. This powerful feature demonstrates Swift’s commitment to providing developers with elegant and expressive language features.

Start leveraging computed properties in your own projects today, and witness the benefits of cleaner, more efficient code! Happy coding! 🚀

Comments