Swift Variables and Constants

by Dimitris Tasios
13 views

In this article, we will see how to declare variables and constants in Swift.

1. Declaring Variables and Constants in Swift

Swift makes it quite easy for us to declare variables and constants. Variables are declared with the var keyword, while constants are declared with the let keyword. A variable can change its value to another value of the same type, while a constant can never change once it’s declared.

To declare a variable with a name myVariable we would write the following:

var myVariable: String = "This is a variable"

Similarly, for a constant named myConstant:

let myConstant: String = "This is a constant"

In our case, our myVariable has a String value of "This is a variable" while our myConstant constant has a String value of "This is a constant".

As we said, a variable can change its value but a constant cannot. So, in this example, we could do the following to our variable:

myVariable = "I have a new value"

But, that’s impossible to do in a constant, since it cannot change its value, so the following will throw a compilation error:

myConstant = "I can't change my value"

It’s also possible to declare multiple variables and constants in Swift on the same line, by simply separating them with commas:

var variable1: Int = 1, variable2: String = "another variable", variable3: Bool = false
let constant1: Int = 5, constant2: Bool = true

As you can see, there is no restriction on the number or types of variables and constants that appear on a single line. However, you cannot have both variables and constants on the same line; you have to pick a side and go on with that.

Lastly, we can declare a variable or constant, based on another variable or constant; not only with literal values (known as “literals”) like 5, "Hello world" or true. The syntax is the same for both variables and constants and we are able to do all of the four possible combinations, as demonstrated below:

var numberFive: Int = 5
let numberTen: Int = 10

var numberFiveVariable: Int = numberFive // 5  - declaring a variable from another variable
var numberTenVariable: Int = numberTen   // 10 - declaring a variable from a constant
let numberFiveConstant: Int = numberFive // 5  - declaring a constant from a variable
let numberTenConstant: Int = numberTen   // 10 - declaring a constant from another constant

However, there is a restriction here: we cannot declare a variable or constant with one type and assign it from a variable or constant of a different type. In other words, we cannot do the following:

let myDouble: Double = 4.5
let myNumber: Int = myDouble

The constant myDouble is a Double while myNumber is an Int. Therefore, this assignment would cause a compilation error.

2. Type Annotations of Variables and Constants in Swift

As you may have noticed, all variables and constants we have declared so far, have explicitly declared their types as well by writing their type (we will talk about all types further below) after a colon (:). This kind of syntax is useful when we want to make sure that a variable or constant is of the type we want them to be. However, it’s not really necessary to explicitly declare the types of variables and constants, as they are implicitly declared by Swift.

var anIntVariable: Int = 55
var anotherIntVariable = 12

As you can see, despite not declaring the type of the second variable (anotherIntVariable), Swift will implicitly declare its type as Int because we assigned it with an integer number. So, if we assigned a Bool value to a variable, that variable would become a Bool variable as well. All these apply to constants as well.

As you might expect, this works in a similar way if we declared a variable or constant from another variable or constant:

let message = "Hello world"
let copiedMessage = message // copiedMessage is a String variable now

Due to the fact that message is a String, assigning it to another variable or constant, in our case copiedMessage, will also make that variable or constant a String. If we wanted to make sure that our copiedMessage must have a specific type, we should explicitly declare it with a colon (:), followed by its type.

3. Types of Variables and Constants in Swift

We have already mentioned some types of variables and constants in Swift. The basic type of variables and constants are:

  1. For integers, Int and UInt
  2. Float and Double, for decimals
  3. For letter based variables and constants, Character and String
  4. Bool

3.1 Int and UInt

Those types of variables and constants represent integers. The difference between them is that the Int type has both negative and positive integers, while the UInt type only has positive (or unsigned) numbers. Both of those types can be found in various sizes, depending on the number of bits they use to represent their values (8, 16, 32, or 64 bits). Respectively the names of those types are Int8/UInt8, Int16/UInt16, Int32/UInt32, Int64/UInt64. The size of Int/UInt depends on the machine, so it’s either 32 or 64 bits.

//Int
let smallestInt = Int.min // -9223372036854775808
let largestInt = Int.max  // 9223372036854775807

// UIInt
let smallestUInt = UInt.min // 0
let largestUInt = UInt.max  // 18446744073709551615

Whenever declaring a variable or constant with an integer literal, without declaring its type explicitly, it automatically becomes an Int.

let anInteger: Int = 5  // this is an Int
let anotherInteger = 5  // this is also an Int
let aUInteger: UInt = 5 // this is a UInt

3.2 Float and Double

Those types represent decimal numbers, known as floating-point numbers. Their difference is in their precision/size: a Float has a precision/size of 32 bits while a Double has a precision/size of 64 bits.

let aFloatNumber: Float = -5.2      // this a Float
let aDoubleNumber: Double = 15.986  // this a Double
let anotherDouble = 54.0            // this is also a Double

As with the integers, a decimal number is by default a Double. If we want to create a Float variable or consonant, we have to explicitly declare it as such.

3.3 Character and String

A Character represents a simple character while a String represents an array of characters, forming words. A Character or String value must be enclosed in quotation marks (""). Once again, a single character value in quotation marks is considered a String, if we do not define the type of variable or constant. You can read more about String and Character in Swift in our article here.

let letterD: Character = "D"            // this is a Character
let aWord: String = "Let's learn Swift" // this is a String
let letterString = "C"                  // this is also a String

3.4 Bool

Lastly, a Bool type represents a Boolean value, which is a value of either true or false. No other values are acceptable in this type.

let aTrueBool = true
let aFalseBool = false

4. Naming Variables and Constants

In Swift, the names of variables and constants have to obey the following rules:

  1. They have to start with a letter or an underscore (_)
  2. Starting with a number isn’t allowed, however, they can contain a number inside them.
  3. They cannot contain whitespaces ( ) or special symbols including arrows or mathematical symbols.
  4. They cannot be the same as the reserved keywords, like for, let, if, true etc. The only way to use those names is by surrounding them in backticks (`).
let _underscoreConstant = "_"   // names can begin with an underscore
let year2022 = 2022             // numbers that are not in the beginning of the name (the first character of the can't be a number)
let 😏 = "smirk"                // names of variables can be emojis
let ελληνικά = "greek"          // different alphabets

var `for` = "for"               // even reserved keywords, surrounded in backticks (`)
`for` = "for loop"              // always used with backticks

A few conventions that should be followed when naming variables and constants are:

  1. Try to avoid using reserved keywords as variable and constant names.
  2. Give descriptive names to variables, instead of names such as a, x or num. A good descriptive name makes the code much easier to read and clearly defines the purprose of the variable/constant.
  3. Finally, if the name of your variable or constant is more than one word, use the camel case to name them. For instance, if your variable or constant defines the favourite food of a person, it should be named favouriteFood.

5. Printing Variables and Names

One of the most common commands of any programming language is the command to print a value to the console. In Swift, this can be done with the print() function (there are multiple different print functions but we’ll focus on the simplest one for this article).

Whenever we want to print a variable or constant on its own, we can simply use the print() function with the variable or constant as its parameter. On the other hand, if we have to include our variable or constant within another String, we have to use a backslash (\) and then enclose the variable or constant in parentheses.

let myMessage = "Swift is fun!"
print(myMessage)                                    // printing only our constant
print("My message to the world is: \(myMessage)")   // printing our constant as part of another String

For the second print() function, Swift uses string interpolation in order to replace the variable or constant with its value when needed.

6. Conclusion

By now, you should be able to declare and use variables and constants in Swift without any issue. You can find the source code (Playground) on our GitHub page.

7. Sources

[1]: The Basics – Swift.org

Related Posts