1.

Take a look at the code snippet given below. Will the given code fail to compile? If yes, why?

Answer»

public class TemperatureClass { private(SET) var temp: Double = 50.0 public func changeTemperature(_ temp: Double) { self.temp = temp }}let temperatureClass = TemperatureClass()temperatureClass.changeTemperature(72.3)public struct TemperatureStruct { private(set) var temp: Double = 50.0 public MUTATING func changeTemperature(_ temp: Double) { self.temp = temp }}let temperatureStruct = TemperatureStruct ()temperatureStruct.changeTemperature(72.3)

Yes, the code given will FAIL to compile because of the last line of the code. The TemperatureStruct has a mutating method to change its INTERNAL variable temp, which is correctly declared. Because we called changeTemperature on an object generated using let, which is immutable, the compiler gives an error. To make the example compile, change let to var.

Methods that affect the internal state of a structure must be MARKED as mutating, but they cannot be invoked from immutable variables.



Discussion

No Comment Found