Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any gain in Swift by defining constants instead of variables as much as possible?

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?

like image 791
Duck Avatar asked Jul 09 '14 09:07

Duck


People also ask

Why would you use a constant instead of a variable?

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.

What is the difference between a constant and a variable in Swift?

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.

How do you define a constant variable in Swift?

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.

Is there Const in Swift?

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.


1 Answers

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.

like image 88
Sulthan Avatar answered Sep 22 '22 04:09

Sulthan