Reputation: 15052
The iterator is mutable for a class:
var selections: [Selection] = []
class Selection {
var selected: Bool
init(selected: Bool) {
self.selected = selected
}
}
selections.forEach({ $0.selected = false }) // This works
but not mutable for a struct:
var selections: [Selection] = []
struct Selection {
var selected: Bool
}
selections.forEach({ $0.selected = false }) // This doesn't work because $0 is immutable
Upvotes: 2
Views: 1842
Reputation: 16660
It is not true, that structures are immutable. But you change a different instance of the structure.
Swift obfuscates the way objects and structures are treated.
Objects are reference types, structures are value types. That means, that iterating over objects passes a reference to the object as argument and changing the object that the reference points to, is changing the the original object.
Structures are value types. A new instance of the structure is passed as argument. Moreover it is constant in this case. But even if you could change this, this would not effect the original instance of the structure.
In other programming language this different level of indirection is visible, i. e. in Objective-C by an *
. In Swift it isn't.
Upvotes: 4