Mutating methods can have the compiler emit “cannot use mutating member on immutable value” errors. For example:
// Error: cannot use mutating member on immutable value let e = [1, 2, 3].makeIterator().next()
To avoid this error, one has to use a mutable variable:
// OK var i = [1, 2, 3].makeIterator() let e = i.next()
Yet, sometimes, one does not care about the mutated value, but only about the result, or the side effects, of the mutating method. In this case, the mandatory declaration of the mutable variable hinders code legibility, and is only a matter of pleasing the compiler.
Here are some other examples that use imaginary of actual APIs:
// Wish we could ignore the modified scanner that has gone // past the first line. // // But error: cannot use mutating member on immutable value let firstLine = Scanner(string: "...").nextLine() // Wish we could ignore the modified Player that is given an id after // its insertion in the database. // // But error: cannot use mutating member on immutable value try Player(id: nil, name: "Arthur").insert(database)
This error has another undesired consequence: mutating methods can not be used in expressions. One has to use several statements instead. Good bye privileged single-line closures. Good bye streamlined functional expressions.
Do you think that it would be worth working on relaxing the “cannot use mutating member on immutable value” error? Assuming it would not bring unsolvable inconsistencies in the language, of course.
If so, we could also look at the “cannot pass immutable value as inout argument” error, which is quite similar in that it also prevents one from ignoring irrelevant mutations.