Swift Tutorial · Collections and Types · Lesson 13 of 30

Swift Structs

Define value types with stored and computed properties, methods, mutating methods and memberwise initializers.

Create a free account to save this page, take notes and track your progress. Sign in

Structs are value types

Structs are the default way to model data in Swift. They get a free memberwise initializer, and copies are independent. A method that changes a property must be marked mutating.

A struct with a mutating method
struct Point {
    var x: Int
    var y: Int

    mutating func move(dx: Int, dy: Int) {
        x += dx
        y += dy
    }
}

var a = Point(x: 1, y: 2)       // memberwise initializer
var b = a                       // a copy
b.move(dx: 10, dy: 0)
print(a, b)
print(a.x == 1)
a.move(dx: 0, dy: 1)
print(a)

Output

Point(x: 1, y: 2) Point(x: 11, y: 2)
true
Point(x: 1, y: 3)

Run this on your computer — see “Get Started” for setup.

Computed properties and observers

A computed property calculates its value each time; didSet runs after a stored property changes.

Computed properties and didSet
struct Cart {
    var items: [Double] = [] {
        didSet { print("cart changed: \(items.count) items") }
    }
    var total: Double { items.reduce(0, +) }       // computed
    var isEmpty: Bool { items.isEmpty }
}

var cart = Cart()
cart.items.append(12.5)
cart.items.append(30)
print(cart.total, cart.isEmpty)

Output

cart changed: 1 items
cart changed: 2 items
42.5 false

Run this on your computer — see “Get Started” for setup.

Test yourself

Why must some struct methods be marked mutating?

  1. To make them public
  2. Structs are value types, so changing self needs to be explicit
  3. To make them async
  4. Only static methods need it
Show answer

Answer: Structs are value types, so changing self needs to be explicit

Was this page helpful?