SyntaxStudy
Sign Up
Swift Properties and Access Control
Swift Beginner 1 min read

Properties and Access Control

Swift supports stored properties (hold a value), computed properties (calculated on access), lazy properties (initialized on first use), and property observers (willSet/didSet). Access control levels are: open, public, internal (default), fileprivate, and private. They control visibility across modules and files. Property wrappers (@propertyWrapper) encapsulate common property patterns, popularized by SwiftUI with @State, @Binding, @Published, and @ObservedObject.
Example
class BankAccount {
    private var _balance: Double = 0

    // Computed property with get/set
    var balance: Double {
        get { _balance }
        set {
            guard newValue >= 0 else { return }
            _balance = newValue
        }
    }

    // Property observer
    var owner: String = "" {
        willSet { print("Changing owner from \(owner) to \(newValue)") }
        didSet  { print("Owner changed from \(oldValue) to \(owner)") }
    }

    // Lazy property
    lazy var report: String = {
        "Account for \(owner): $\(balance)"
    }()

    func deposit(_ amount: Double) {
        guard amount > 0 else { return }
        _balance += amount
    }
}

// Property wrapper
@propertyWrapper
struct Clamped<T: Comparable> {
    var value: T
    let range: ClosedRange<T>

    var wrappedValue: T {
        get { value }
        set { value = min(max(range.lowerBound, newValue), range.upperBound) }
    }

    init(wrappedValue: T, _ range: ClosedRange<T>) {
        self.range = range
        self.value = min(max(range.lowerBound, wrappedValue), range.upperBound)
    }
}

struct Player {
    @Clamped(0...100) var health: Int = 100
}

var player = Player()
player.health = 150
print(player.health)  // 100