iOS Closures in Swift First Class Functions Capturing Variables

var or let

Hello everyone. Just wondering, I know it's a reference type, but just to clear some things up. What would had happened if the teacher had used a variable instead of a constant? It's the same result right? Or what is the difference?

1 Answer

Wouter Willebrands
Wouter Willebrands
iOS Development with Swift Techdegree Graduate 13,121 Points

Hi Oscar,

It depends on the occasion what happens when a constant is changed to a variable, but in most cases this won't be a problem. However if you define something as a variable, but afterwards you are not mutating it in any way in your code, the compiler will suggest you change it into a constant (let) instead.

It is often good practice to define properties as constants, and change it to var if the compiler informs you that you're trying to mutate a constant, instead of the other way around. This prevents you from accidentally mutating a property that would allow your app to crash.

I hope this answers your question.

Kind regards,