user7088216
user7088216

Reputation:

cannot use mutating member on immutable value: 'XXX' is a 'let' constant

i am new to swift .i am trying with several way but i failed when try as suggest error then anther error occur . what is going on exactly here i don't know

  public struct ThermometerStruct {
          var temperature: Double = 0.0
      public mutating func registerTemperature(temperature: Double) {
        self.temperature = temperature
      }
    }

    let thermometerStruct = ThermometerStruct()
    thermometerStruct.registerTemperature(temperature : 56.0)

ERROR at line 14, col 5: cannot use mutating member on immutable value: 'thermometerStruct' is a 'let' constant thermometerStruct.registerTemperature(temperature : 56.0) ^~~~~~~~~~~~~~~~~

INFO at line 13, col 5: change 'let' to 'var' to make it mutable let thermometerStruct = ThermometerStruct() ^~~ var

Upvotes: 6

Views: 13687

Answers (2)

Mehrdad
Mehrdad

Reputation: 1208

In case you're using lazy var in structs and you're passing it to a function or having a let refference of the object, accessing the lazy var is implicitly mutating to the object.

so you need make a var out of it.

struct Test {
  lazy var a: String = ""
}

...

func something(test: Test) {
    let a = test.a //throws compile error

    var test = test
    let a = test.a //OK
}

Upvotes: 6

FelixSFD
FelixSFD

Reputation: 6092

The error-message already tells you, what you need to change. Replace let with var.


structs ar value types. This means, if any property of a struct is modified, the instance needs to be declared as var.

When your struct has a method, that is modifying one of the struct's properties, this method is mutable. mutable methods can only be called on instances you have declared as var.

Upvotes: 8

Related Questions