Reputation:
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
Reputation: 1208
In case you're using lazy
var in struct
s 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
Reputation: 6092
The error-message already tells you, what you need to change. Replace let
with var
.
struct
s 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