0Pricing
Swift Academy · Lesson

Non-mutating Alternatives

Return new values instead of mutating in place.

Return Instead of Mutate

Instead of changing an instance in place, a non-mutating method can return a brand-new value with the change applied.

struct Counter {
    var value: Int
    func incremented() -> Counter {
        return Counter(value: value + 1)
    }
}
let c = Counter(value: 0)
let next = c.incremented()
print(c.value, next.value)

Original Stays Unchanged

Because nothing is mutated, the original value is preserved and a new value is produced.

struct Vector {
    var x: Int
    var y: Int
    func scaled(by factor: Int) -> Vector {
        return Vector(x: x * factor, y: y * factor)
    }
}
let v = Vector(x: 2, y: 3)
let big = v.scaled(by: 10)
print(v.x, v.y, big.x, big.y)

All lessons in this course

  1. Value Types and Immutability
  2. The mutating Keyword
  3. Mutating and self Reassignment
  4. Non-mutating Alternatives
← Back to Swift Academy