Swift 101: Constants and Variables

In Swift, constants are values that never change while variables are values that can change. For both constants and variables, different types of values can be assigned including strings, integers, arrays, etc. A constant uses ‘let’ while a variable uses ‘var’.

Constant Example

A player’s device in a game could be a constant if it won’t change.

let playerDevice = "iPhone"

This constant stores the player’s device as a string. Because it is a constant, it’s value cannot change.

playerDevice = "iPad" // This will produce an error.

Variable Example

A changing value, such as a score, can be stored as a variable.

var score = 20

This variable stores the player’s score as an integer. Later in code, this value can change. For example:

score = 21

Data Types

There are many more data types than just strings and integers in constants and variables.

String: Usually text or a combination of text and numbers. Emojis can also be used in a string data type.

Int: Integers are whole numbers that don’t contain decimal places like 2, 73, -29, etc.

Double and Float: These are numbers with decimal places like 1.75, 9.49, etc. Double can contain many more decimal places than float for a more precise measurement.

Bool: This is a very simple data type, either true or false.

There are other types of data, but these are the most common.