I'm learning Swift language now a days.
In Apple's documentation I saw a example for extension like:
extension Int: ExampleProtocol {
var simpleDescription: String {
return "The number \(self)"
}
mutating func adjust() {
self += 42
}
}
7.simpleDescription
So I just called the adjust()
like:
7.adjust()
It throws an error:
Immutable value of type `Int` only has mutating members named adjust.
I'm not sure what causes the error ? Can anybody help me to understand the issue ?
The adjust method is marked as mutating meaning that it changes the thing the method is being called on.
7 is a literal so it doesn't make sense to change it's value. Literals cannot be mutated. That is why the error message says that the immutable value cannot be mutated.
Instead, you can use that method on a variable (that is mutable):
var myNum = 7
myNum.adjust()
println(myNum) // 49
If you were to try the same thing on a constant, you would get the same error message since it is also not mutable:
let myNum2 = 7
myNum2.adjust() // Error: Immutable value of type 'Int' only has mutating members named 'adjust'