2

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.

Swift Error

I'm not sure what causes the error ? Can anybody help me to understand the issue ?

Midhun MP
  • 103,496
  • 31
  • 153
  • 200

1 Answers1

6

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'
drewag
  • 93,393
  • 28
  • 139
  • 128
  • Ohh, my bad. I didn't think about it. Thanks for your answer :) – Midhun MP Dec 20 '14 at 05:55
  • 1
    Strictly speaking this is not attempting to mutate a literal. This is attempting to mutate the immutable Int that is returned from `init(integerLiteral: 7)` – Airspeed Velocity Dec 20 '14 at 12:38
  • @AirspeedVelocity good point. I think the conceptual nature of that is more difficult so I will leave my answer as is. – drewag Dec 20 '14 at 19:30