Like in C and Objective-C and pretty much every other programming language in existence, Swift uses constants and variables to store the values in your application. In this article, we’re going to look at variables and constants in Swift.
- Rules for Naming Variables
- Declaring Variables
- Type Annotations
- Assigning Values to Variables
- Type Inference
- Declaring Constants
- Why Use Constants?
- Initialising Constants
- Declaring and Initialising Multiple Variables and Constants on a Single Line
- Printing Constants and Variables
Rules for Naming Variables
As with other languages, constants and variables in Swift associate a name (such as
playerName) with a value of a particular type (such as the number
10 or the string
When naming variables and constants in Swift there are a few rules and recommendations you need keep in mind.
As with some other languages, the recommendation in Swift is to use a camel case naming convention when naming variables.
If you’re not aware of camel case, it is a naming convention that uses a lowercase letter for the first word in a variable name followed by a capital letter for each subsequent word.
We’ve already seen a couple of examples of this –
playerName both follow this convention.
Beyond the recommendation to use camel case, there are also some hard and fast rules that you must adhere to.
The first is that variable names cannot contain whitespace characters, mathematical symbols (such as the plus (
+) or minus (
-) operators) or certain Unicode values or line and box drawing characters.
The main reason for this is to ensure that the Swift compiler is able understand where the names of our variables start and where they finish. For example if you had a variable named
this being added to
That or is it a single variable name?
In addition to not being able to contain certain characters, variable names also can’t begin with a number (although you can use numbers later in the name). For example, the variable name
2fast is invalid but
multiplyBy2 is valid.
Beyond that though, variable names can contain almost any other character you like including unicode characters. By allowing unicode characters in variables names Swift opens up all sorts of naming options, including the use of emoji characters to name your variables (though I wouldn’t recommend it).
As with naming conventions you might be familiar with from other languages, when naming variables, try to choose names that express something about the values that the variables will be holding. This helps people reading your code to get a better idea of what sort of information you’re storing and imparts a better understanding of how those values are likely to be used.
Now, as with other languages, variables in Swift must be declared before they are used.
In Swift, variables are declared using the
var keyword followed by the name of the variable you want to declare, a colon and then the type of value you want to store in that variable:
var currentScore : Int
Let’s break it apart piece by piece.
First, we’ve got the
var keyword. This tells Swift that we want to declare a variable.
var keyword we then have the name of the variable. In this case I’ve called it
In naming the variable I’m following the camel case naming convention I mentioned above. In doing so I have started the variable name with a lowercase
c and have then capitalised the first letter of the next word
After the variable name is a colon, a space, and then the type of information we’re going to store in the variable. In this case I’ve declared the variable to store values of type
In Swift, the colon, space, datatype combination is referred to as a type annotation. Think of the type annotation as specifying the type of thing or kind of thing that the variable is going to hold.
If we put it all of the pieces of the declaration together then, you can read the variable declaration as follows:
“Declare a variable called
currentScorethat can store any value of type
At is core, Swift is a type-safe language and as such, Swift encourages you to be explicit about the types of values that your variables and constants are going to hold.
By forcing us to be explicit, the Swift compiler can use the type information we provide to check our code and ensure that the values we’re assigning are of the right type.
If they’re not, it can warn us of that fact by raising an error and giving us information about the problem it found. Ultimately this helps us write better code with fewer bugs.
Now, I’ve gone over some of the different data types in other posts but for now, know that in situations like this, where you’re not assigning an initial value to a variable, you have to use a type annotation. It’s not optional.
If I hadn’t provided a type annotation here and also hadn’t provided a initial value, the compiler would have no way of working out what type of values I wanted to store.
One other thing to note is that once you have declared a variable (or a constant) to hold values of a specific type (whether that be through a type annotation or through another mechanism we’ll look at shortly called type inference), you can’t redeclare that constant or variable later in your code to hold values of a different type. Think of declaring the types of values a variable or constant will store as a one-shot deal. Once you’ve declared it to be of a particular type, that’s it, it’s defined to hold values of a certain type and you can only assign values of that type to the variable.
So we’ve looked at how we can declare a variable and tell the compiler what type of data we’re going to store, lets next have a look at how we assign and store values in it.
Assigning Values to Variables
Assigning An Initial Value to a Variable
Assigning an initial value to a variable is extremely simple. All you have to do is to use the assignment operator (
=) followed by the value you want to assign.
Remember though, that we’ve already told the compiler the type of values that we’re going to store so we must make sure that we assign a value of the correct type.
To see what happens if you fall to do this, let’s start off by trying to assign a value of the incorrect type. Let’s use the
currentScore variable as an example:
// This will raise an error.
var currentScore = “Andy”
If you’re following along in a Playground, Xcode should show you an error.
This is the compiler telling you that you’ve made a mistake.
To see the error message in full, all you have to do is click on the red cross in the gutter and Xcode will show you the full error message:
Cannot convert value of type `String` to specified type `Int`
So what is this telling you?
Well, in this case, the compiler is giving you a pretty clear hint.
Remember that we’ve already declared the
currentScore variable to hold values of type ‘Int’. In this case, we’ve tried to assign it a value of
“Andy” which is actually a string of characters. Strings of characters are represented by the
String type in Swift. We’ll look at the
String type at a future data but the point here is that it isn’t an
Int which is what the compiler is looking for.
In this case, the compiler is telling us that it can’t convert the value of type
String (in this case
”Andy”) into a value of type
Int (a whole number) and if you think about it, that’s pretty logical.
So now we know what the problem is, let’s fix it.
// This is valid
var currentScore : Int = 0
Here I’ve deleted the
String value and instead replaced it with a zero (
0). In Swift the numeric digit zero is interpreted to be a number of type
This should clear the error and the compiler should now be happy that we’re assigning a value of the correct type.
Assigning New Values to Variables
Ok, so we’ve seen how to declare a variable and also seen how to initialise it with a value but what about assigning it a new value?
Let’s suppose I’d earned, say 100, points and wanted to set the new score. All I have to do is use the assignment operator (
currentScore = 100
Notice this time that I didn’t use the
var keyword again. The
var keyword is only used when you declare a variable, not when you assign a new value to it.
Once a variable is declared, you can simply assign new value to it by using the assignment operator. You don’t have to include the
var keyword again and in fact, if I had tried to use the
var keyword again, I’d have gotten an error from the compiler warning me that I was trying to redeclare the variable.
Now, if you’re a bit lazy like me, declaring a variable like this is a whole bunch of typing and to help us out with this, Swift has a built in mechanism called type inference that helps us reduce the amount information we need to provide.
As we’ve seen, when we declare a variable, we can provide an initial value for a variable at the point we declare it, just as we’ve done with the
currentScore variable here.
When we do this, we have the option of using a kind of short-hand notation for declaring a variable.
If we assign an initial value to a variable at the same time as we declare it, Swift lets us drop the type annotation from the declaration and instead lets the compiler infer the type of data we want to store based on the initial value we assign.
So for example we could write:
var playerName = “Andy”
Notice how I didn’t use a type annotation (the colon, space, type name) in the declaration.
Here I’m essentially saying:
“Declare a new variable called
playerNameand give it an initial value of
Andybut infer the types of values that will be stored in it from the initial value I provide”.
In Swift, the type inference mechanism is extremely powerful and can save a bunch of typing. It also helps to make you code shorter and easier to read. So much so that in reality it’s relatively rare to write type annotations explicitly as in practice you’ll usually provide an initial value when you first declare a constant or variable, letting the Swift compiler simply infer the type for you.
So, we’ve covered variables, lets take a look at their counterparts; Constants.
The primary difference between constants and variables in Swift is that where variables can have multiple values during their lifetime, constants can have only one.
Once you’ve assigned a value to a constant in Swift the constant becomes immutable. This means that the value stored in it cannot be changed. This is different from variables which are always mutable meaning that the values stored in them can change (or vary) at any time (hence the name variable).
In Swift, constants are declared using the
In a similar fashion to variables, the
let keyword is followed by the name of the constant you want to declare and then a type annotation (a colon, a space and then the type of data you want to store in the constant).
When it comes to naming constants, all the same rules and recommendations we saw with variables still apply and as with variables, this includes the recommendation to follow the camel-case naming convention.
If you’re coming from another programming language, this may seem a little strange.
In other languages, constants are commonly written in all uppercase to signify the fact that they are different. In Swift though, constants are given no special consideration. Swift treats them just like variables. There is nothing particularly special about them and as I mentioned, they follow the same naming conventions and rules that we just discussed including the fact that they can’t start with a number and also can’t contain spaces, mathematical symbols or certain Unicode values and line and box drawing characters.
The other things to bear in mind with constants is that as with variables, we can’t declare a constant more than once in your program and we also can’t initially declare something to be a constant and later in our program redeclare it to be a variable or visa versa.
Why Use Constants?
Now, at this point my might be tuning out a little. After all, there’s nothing particularly special about constants but the thing is, constants are one of those things that programmers don’t do very much.
Sure you can declare them, but most of the time the culture surrounding programming languages means that programmers usually don’t use them and if they do, the don’t use them very often. Swift however is different.
In Swift constants are important and commonplace and a much greater emphasis is placed upon using constants in everyday programming, more so than in most other languages you’ll be used to. There are several reasons for this.
Primarily, constants in Swift are used as a safety feature. By using constants everywhere you typically make your programs safer by 100% guaranteeing that you only change the values you expect to and thus helps avoid bugs hard to find bugs.
On top of this, by telling the compiler which values you expect to change in your program and which you don’t, you also get some performance benefits. By telling the compiler which values are going to be constants and which aren’t, the compiler can perform optimisations when it compiles our apps that can help make them run faster. Never a bad thing.
So as you can see there are benefits to using constants instead of variables and Apple strongly recommend that you use them whenever you know a value in your program is not going to change. So with this in mind you really need to try to get into the habit of using the
let keyword whenever you can. My recommendation on this front is to initially overcompensate. Initially, try to declare everything with the
let keyword and only change those things that you really need to back into variables. If you do this, you’ll be surprised just how few of them you really need to change and it’ll get you into the habit of using
let by default.
So we’ve talked about how to declare constants and we’ve talked about why we use them, but how to we assign them their initial values?
In this example, we’re going to declare a constant called
maximumScore to represent the maximum score a player could get in a game:
let maximumScore : Int
We’ve declared the constant using the
let keyword, have then written the name of my constant, a space, a colon and then the type of information that we’re going to hold in my constant (in this case an
As with variables, we can also assign constants a value at the time we declare them. Using the assignment operator we can give the
maximumScore constant a value of 1000 at the time we declare it:
let maximumScore : Int = 1000
As with variables, when declaring a constant, we can also make use of type inference to determine the type of data that we want to store. The type inference mechanism we talked about just now works just as well with constants as it does with variables. We could therefore have also written the
maximumScore declaration like this:
let maximumScore = 1000
Declaring and Initialising Multiple Variables and Constants on a Single Line
When it comes to declaring and initialising variables or constants, you also have the option to make multiple declarations on a a single line. This is another short-hand syntax that save a bit of typing.
When declare variables or constants in this manner, we separate each variable or constant and its initial value from the next variable or constant and its initial value by using a comma. For example, we could declare and initialise three variables
z as follows:
var x = 0, y = 2, z = 3
Or two constants as follows:
let lowerLimit = 10, upperLimit = 90
Again, in both these examples we’re making use of type inference and letting the compiler work out the types of data we’re going to store based on the initial values we’ve assigned.
The only thing we need to be aware of is that when you declare multiple variables or constants on a single line you can’t mix and match variable and constant declarations. For example say we wanted to declare a variable
x and a constant
y we can’t write:
var x = 10, let y = 12 // Causes a compiler error.
// `let’ cannot appear nested inside another ‘let’ or ‘var’ pattern.
When we declare multiple variables or constants in this way, all the declarations in the statement need to be either variables or for constants, but not both.
Instead, if we do want to mix and match and declare both variables and constants on the same line (not necessarily a good idea from a clarity point of view) we have to write the variable declarations and constant declarations as separate statements separated by a semi-colon like this:
var a = 0, b = 2, c = 4; let d = 6, e = 8
Printing Constants and Variables
So, we’ve seen how to declare and initialise constants and variables but before we wrap up, lets take a couple of moments to see how we can print out the values that are stored in them.
In a playground, we can achieve this relatively simply.
In a playground, if we write the name of the variable or constant on a line on its own, Xcode will print the current value of that variable or constant over in the output pane.
Now this is great, but often, we want to create and output more interesting messages of our own and in Swift and when running in a full application we don’t have the luxury of the playground. In these cases, to print the value of a variable or constant we use the
printf() function in C, the
System.out.println() function in Java, the
Console.WriteLine() function in C# or the
In Swift, the
print() function is a globally available function (meaning it is available anywhere in your program) and there are various forms of the function that you can call. Essentially they all boil down to a version that takes two parameters though. In this form, the first is the item you would like to print out and the second is an optional termination character, which by default (meaning we don’t always have to supply it), is a line break.
In other languages, when you wanted to print out a compound message made up of a string and a constant or variable, you may have used things like concatenation using the
+ operator or format specifiers where placeholders are inserted within a string. C, C++ and Objective-C all use these approaches. Swift however, uses a different and more powerful mechanism. A mechanism called string interpolation.
Now string interpolation might sound complicated at first but it really isn’t.
If you look up the term interpolate in the dictionary you get the following definition:
“To introduce (something additional or extraneous) between other things or parts; to alter (a text) by the insertion of new matter.”
All interpolation really means then is to take one item, usually text, and insert something else within it. So if we take this idea and extend it to string interpolation we take a string, and insert another, variable (or constant) item inside it. It’s essentially a way of constructing a new string value through a combination of constants, variables, literals (things we literally write in our code) and expressions by including their values inside a string literal.
For example we could use string interpolation take a standard string error message and insert the exact details of the error into the output string, or take a welcome message and insert the users name into the welcome message.
In Swift, string interpolation is extremely simple. All we do is take a string, (a set of characters between double quotes), and add a placeholder to the string for the content that we want to insert.
For the placeholder we use a backslash followed by a set of parentheses and then include whatever we want to include within the string within the parentheses.
Let’s take a look at an example. Say I had this welcome message that I wanted to customise to include the actual name of our player.
var welcomeMessage = “Hello , and welcome.”
The first step is to replace the “ with our string interpolation placeholder which is a backslash and a pair of parentheses. Lets do that now.
var welcomeMessage = “Hello \(), and welcome.”
Right, we’re one step closer. All that remains is to write the name of the variable that contains our users name within the parentheses:
var welcomeMessage = “Hello \(playerName), and welcome.”
In a playground, we can see the resulting of our interpolation by putting the
welcomeMessage variable on a line of its own like this:
However as I just mentioned, in real apps, we wouldn’t normally do this. Instead, we’d make use of the
print() function we saw just now and write the string we wanted to interpolate as a parameter to the
Let me re-write this using the
print() function instead.
print(“Hello \(playerName), and welcome.”)
As you can see, we get exactly the same output, but this version will work in full Swift program, not just in a playground.
So that’s pretty much it for this post. We’ve covered the basics of both variables and constants in Swift, we’ve looked at how we can use type inference to infer the types of our constants and variables and we’ve also looked at how we can use String interpolation to print out the values that are stored in those constants and variables.
As ever, if you have any comments leave them below and if you want to sign up for my weekly newsletter containing a collection of hand-curated links from around the iOS development community make sure you drop your email in the form below.