Kodeco Forums

Intermediate Swift Part 3: Methods

Learn about some of the more advanced features of methods.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/4190-intermediate-swift-2/lessons/4

Hi

Can you please explain why we can use the ‘setter’ method to alter celsius in the fahrenheit section. Yet we have to use mutating func to alter celsius elsewhere?

set {
  celsius = round((newValue - 32) * 5/9 * 100) / 100
}

vs

mutating func updateTemperatureByPercent(percent: Double) {
celsius += celsius * percent/100

}

The first thing I thought during the video was, we already changed celsius before without using mutating func. Thanks

That’s a great question @heaford! You need to mark methods as mutating to signal the compiler that you know it will change some properties. For structs, that means if the instance is declared with let then the compiler will know to disallow through to this method since the instance is immutable.

Setters for stored properties, on the other hand, are inherently mutating. The compiler already knows that for immutable instances, calling through to the setter is not allowed. That means it doesn’t need you to add mutating.

I hope this makes sense. Thanks again for the question and also for subscribing to the videos!

1 Like