Structs and Classes
Mutating Methods
A struct method marked mutating can change the instance's stored properties.
Change a value type
mutating_methods.swift
struct Counter {
var value: Int
mutating func advance(by amount: Int) {
value = value + amount
}
}
let step =
var counter = Counter(value: 10)
counter.advance(by: step)
counter.advance(by: step)
print("step=\(step)")
print("value=\(counter.value)")
struct Counter {
var value: Int
mutating func advance(by amount: Int) {
value = value + amount
}
}
let step =
var counter = Counter(value: 10)
counter.advance(by: step)
counter.advance(by: step)
print("step=\(step)")
print("value=\(counter.value)")
struct Counter {
var value: Int
mutating func advance(by amount: Int) {
value = value + amount
}
}
let step =
var counter = Counter(value: 10)
counter.advance(by: step)
counter.advance(by: step)
print("step=\(step)")
print("value=\(counter.value)")
mutating
Struct instances are values. A `mutating` method is explicit about changing the stored properties of that value.