You might think declaring variables would be something simple to do in Swift and it is. The problem comes with the different ways to declare variables, mostly based on older programming languages.
Here’s the traditional way to declare a variable in an older language. First, you declare a variable and its data type. Second, you give that variable a value. In Swift, this two-step method of declaring variables looks like this:
One problem with this two-step method is if you forget to define a value to a variable and then later try to use that variable, your program could crash because the value of that variable is undefined.
For a more advanced way to declare variables, use just one step. Declare the variable as a particular data type and then assign a value to it right away. In Swift, this second way to declare a variable looks like this:
By following this practice of assigning a value to a variable as soon as you declare it, you minimize the risk of leaving a variable without a specific value, even if that value is only temporary. However, declaring a variable name, its data type, and its value is cumbersome. That’s why Swift offers a third way to declare variables and assign them values by simply eliminating the data type.
Essentially, data types mean the variable can hold a number or a string. A number could be an integer or a decimal number. So it’s often much simpler to use this third method of Swift of eliminating the data type completely.
In Swift, this is called inferring the data type, which means you just need to assign a value to a variable and Swift infers the data type like this:
Any time you assign a string to a variable, Swift assumes the variable data type is String.
Any time you assign an integer to a variable, Swift assumes the variable data type is Int.
Any time you assign a decimal number to a variable, Swift assumes the variable data type is Double.
Sometimes it’s better to specify exactly the data type you want to use. For example, if precision isn’t that important, then just use a Float data type for a decimal number instead of Double. Since Float data types store less precision, they take up less memory as well.
So the three ways to declare a variable are:
- Declare a variable as a data type, then assign a value to that variable on another line
- Declare a variable as a data type, then assign a value to that variable on the same line
- Declare a variable by assigning a value to that variable on the same line
For simplicity, the third method of letting Swift infer the data type is shortest and easiest. For clarity, the second method of declaring a data type and assigning a value to it is clearer. In general, avoid the first method of declaring variables because it’s too easy to forget to assign a value to a variable by mistake.
Even something as simple as declaring a variable in Swift takes thought. If you think ahead, you can always make programming easier in the long run.