In a protocol, you declare a method signature that you think needs to mutate the instance conforming to the protocol as “mutating”, so that structs can mutate its data for the protocol as well.
I have never actually used this feature before. But more to the point, why can’t Swift just allow structs to adopt to a protocol without needing that protocol to declare a function as mutating.
I guess you've already used that feature because it is adopted by IteratorProtocol, which requires mutating func next() -> Self.Element?.
e.g.
Given the following code,
for i in 0..<100 { ... }
IndexingIterator<Range<Int>>'s mutating func next() -> Int? is called.
The following code cannot be compiled because IteratorProtocol requires func next() to be a mutating function.
let iter: any IteratorProtocol<Int> = (0..<100).makeIterator()
_ = iter.next() // ❌ error: cannot use mutating member on immutable value: 'iter' is a 'let' constant
I wonder what you expect to happen if func next() were not required as a mutating function.
Should this code be successfully compiled, even though IndexingIterator<Range<Int>> is a struct and its func next() -> Element? is marked as mutating?
I didn’t realize you cannot mutate a let value. I thought it just meant you cant change the value it’s assigned to. Presumably if we change the struct’s data then it’s still the same value referred to by the let.
In this way the protocol wouldn’t need to care about mutability.
If you mutate a struct, you get a new copy of the struct, with the change - the original one goes away. [edit - that's not strictly true: Why are structs in Swift said to be immutable?]