Junior — Middle
Is it possible to declare methods that modify the state of objects in classes in Swift?
sobes.tech AI
Answer from AI
In Swift, methods that modify the state of an object are declared with the mutating keyword, but this applies only to structures and enumerations (value types). For classes (reference types), methods can modify the instance properties by default without any additional keyword.
That is:
- In classes, you can declare methods that change the object's state without
mutating. - In structures and enumerations, methods that modify properties must be marked as
mutating.
Example of a class with a modifying method:
class Counter {
var count = 0
func increment() {
count += 1
}
}
let counter = Counter()
counter.increment()
print(counter.count) // 1
Example of a structure with a mutating method:
struct Counter {
var count = 0
mutating func increment() {
count += 1
}
}
var counter = Counter()
counter.increment()
print(counter.count) // 1