</>
Skip to content
Swift lessons (22/33)

Swift — Properties

Stored properties

struct Person {
    var name: String
    let id: Int
}

let p = Person(name: "Alice", id: 1)
// p.id = 2 // Error: let is constant

Computed properties

struct Rectangle {
    var width: Double
    var height: Double

    var area: Double {
        width * height
    }

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

let r = Rectangle(width: 5, height: 3)
print(r.area)       // 15.0
print(r.perimeter)  // 16.0

Property observers

struct StepCounter {
    var totalSteps: Int = 0 {
        willSet {
            print("About to set to \(newValue)")
        }
        didSet {
            print("Changed from \(oldValue) to \(totalSteps)")
        }
    }
}

var counter = StepCounter()
counter.totalSteps = 200
// About to set to 200
// Changed from 0 to 200

Lazy properties

struct DataImporter {
    var fileName: String
    init(fileName: String) {
        self.fileName = fileName
        print("Importing \(fileName)")
    }
}

struct DataManager {
    lazy var importer = DataImporter(fileName: "data.txt")
    var data: [String] = []
}

let manager = DataManager()
print("Manager created")
manager.data.append("item")
manager.data.append("item")
// importer created only when first accessed
print(manager.importer.fileName)

Type properties

struct MathHelper {
    static let pi = 3.14159

    static func square(_ x: Double) -> Double {
        x * x
    }
}

print(MathHelper.pi)
print(MathHelper.square(5))

Property wrappers

@propertyWrapper
struct Clamped {
    var wrappedValue: Int {
        didSet { wrappedValue = min(max(wrappedValue, range.lowerBound), range.upperBound) }
    }
    let range: ClosedRange<Int>

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

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

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

Mini Practice

Write Swift code that:

  1. Creates a computed property
  2. Uses property observers
  3. Demonstrates a lazy property
  4. Creates a property wrapper

Up Next

In the next lesson, you'll learn about Methods — functions on types.

Related Topics

Frequently Asked Questions about Properties

What is Properties in Swift?

Properties is a fundamental concept in Swift. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Properties?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Properties.

Why is Properties important in Swift?

Properties is essential for Swift development. Understanding this concept will help you write better code and solve real-world problems more effectively.