Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the benefits of `let` in Swift?

I know Swift does encourage us programmers to use constants (let) instead of variables (var) everytime it makes sense.

This is a good thing because we are providing more details to the compiler about what our code means and the compiler can better prevent us from making mistakes (e.g. changing some value that should not be changed).

My question is, are there some performance optimizations the compiler does apply when we use constants instead of variables? (e.g. faster executions times, lower footprint, ...).

like image 306
Luca Angeletti Avatar asked Jul 27 '15 11:07

Luca Angeletti


People also ask

Why do we use let in Swift?

In swift, we use the let keyword to declare a constant variable, a constant is a variable that once declared, the value can not be changed.

Is Let immutable in Swift?

Let is an immutable variable, meaning that it cannot be changed, other languages call this a constant.

What is let in Xcode?

Swift lets you create both variables and constants as ways to reference your data, but there's a strong push (even Xcode warnings!) if you create things as variables then never change them. To make a constant, use let like this: let x = 10.

What's the difference between VAR and let Which one would you choose for properties in a struct and why?

Since classes are reference objects the only difference between let and var is the ability to reassign the variable to a different class of the same type. The let and var keywords do not affect the ability to change a variable on a class.


1 Answers

You asked "...are there some performance optimisations the compiler does apply when we use constants instead of variables?"

The answer is yes, absolutely.

Mutable collections may be organized differently than immutable ones in order to allow for them to be changed. Immutable collections can be optimized for read-only operation.

Then there is the use of mutable/immutable objects. The compiler may have to generate code that copies a mutable object when it's shared as a property of another object in order to avoid undesired side-effects.

Comparison of immutable objects (equatable/comparable) can also be optimized in ways that mutable objects can't.

Sulthan's point about the intelligence of the compiler is a good one though. The compiler can often deduce that a variable is never going to change from code analysis, which can make benchmarking let vs. var usage hard.

like image 179
Duncan C Avatar answered Oct 05 '22 08:10

Duncan C