Thuta Learning
AdvancedProgrammingbeginner

Properties

Relax. We'll talk through this in plain words — no textbook voice.

Properties are the variables and constants that hold data inside a struct/class/enum. A stored property actually holds the data. A computed property, on the other hand, calculates its value based on other data.

swift
struct Product {
    var name: String
    var price: Double
    var discountPercent: Double

    var finalPrice: Double {
        price - (price * discountPercent / 100)
    }
}

let plan = Product(name: "Pro Plan", price: 20.0, discountPercent: 10)
print("\(plan.name): $\(plan.finalPrice)")

name, price, discountPercent are stored properties. finalPrice is a computed property that calculates the discount and returns the result.

You should see
Pro Plan: $18.0

Easy traps

  • If a computed property's logic ends up calling itself, you'll get infinite recursion.
Properties | Thuta Learning