D
D
driverx182019-06-13 22:27:18
Swift
driverx18, 2019-06-13 22:27:18

Why do I see more use of let than var in Swift?

I'm watching Swift lessons, and it's not entirely clear why (many different people) often write mostly let, rather than variables? (It seems often to unpack optionals)
Yes, I know that years is a constant, but I came to swift from php, and variables are often used there, and constants for special cases. Let gives a profit in memory, or some other reason?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
doublench21, 2019-06-14
@driverx18

The immutability of a variable is a rather important property. Variables need to be marked with a keyword for leta reason. Let's omit the obvious, coming from the definition - immutability. But what is behind this at the compiler level? And there are things behind it.
If you think broadly, then you can mark with a keyword letnot only, say, a variable containing a number, but a collection or structure or object.
A collection marked as immutable allows the compiler to allocate contiguous memory for it, which will speed up the read operation compared to a regular, dynamic collection. (It is for this reason, for special needs, that Swift has a special collection of ContiguousArray )
For mutable objects, the compiler may need to generate code that copies the mutable object when it is used as a property of another object, but for immutable objects, we don't get extra code.
Comparison for immutable objects can also be optimized by the compiler.
Even for ordinary structures, methods that change the fields of the structure must be marked with a keyword mutable. In turn, this also does not just happen.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question