Is there any gain in speed, memory usage, whatever, in Swift by defining as much as possible constants x vars?
I mean, defining as much as possible with let
instead of var
?
Constants are used when you want to assign a value that doesn't change. This is helpful because if you try to change this, you will receive an error. It is also great for readability of the code. A person who reads your code will now know that this particular value will never change.
Constants and variables associate a name (such as maximumNumberOfLoginAttempts or welcomeMessage ) with a value of a particular type (such as the number 10 or the string "Hello" ). The value of a constant can't be changed once it's set, whereas a variable can be set to a different value in the future.
Swift employs the keywords let and var for naming variables. The let keyword declares a constant, meaning that it cannot be re-assigned after it's been created (though its variable properties can be altered later). The var keyword declares a new variable, meaning that the value it holds can be changed at a later time.
Every useful program needs to store data at some point, and in Swift there are two ways to do it: variables and constants. A variable is a data store that can have its value changed whenever you want, and a constant is a data store that you set once and can never change.
In theory, there should be no difference in speed or memory usage - internally, the variables work the same. In practice, letting the compiler know that something is a constant might result in better optimisations.
However the most important reason is that using constants (or immutable objects) helps to prevent programmer errors. It's not by accident that method parameters and iterators are constant by default.
Using immutable objects is also very useful in multithreaded applications because they prevent one type of synchronization problems.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With