DEV Community

Cover image for Intro to Swift: Constants and Variables
Joshua Rutkowski
Joshua Rutkowski

Posted on • Updated on

Intro to Swift: Constants and Variables

This lesson is a companion to my Twitter ✨Intro to Swift✨ crash course - Check it out! 👌

The lesson introduces you to the Swift programming language and mainly covers constants and variables and the print statement.

Objectives for this lesson:

  • Learn to use Xcode to create a playground
  • Learn to use print() to output text to the console
  • Learn to use constants (let) to store values
  • Learn to use variables (var) to store and change values
  • Learn when to use var vs let
  • Learn to use different types of variables and constants, including Int, Float, Bool, etc.

The lesson concludes with the following Challenge:

Create variables and constants for various parts about you, such as your name, your hometown, your favorite color and food, and anything else you think someone would be interested to know about you. Think about which of these should be variables, and which should be constants. Try to come up with at least 8 constants and variables in total.

Print each of these using print() statements and inserting the variable or constant in the parentheses.

Note: This lessons follows along Lambda School's iOS 101 precourse work. For additional information on Lambda School's iOS Development course, click here.

Learn to use Xcode to create a playground

Xcode includes a feature called playgrounds. Playgrounds provides a testing ground that renders developer code in real time.

To start a new playground, open Xcode and select "Get started with a playground." Don't have macOS or Xcode? No worries, head on over to repl.it

Alt Text

Learn to use print() to output text to the console

In its simplest form, a print statement looks like this:

print("Text you want to output here")

In Xcode, the print() function prints its output in Xcode’s “console” pane, as seen below.

Alt Text

Learn to use constants (let) to store values

Constants associate a name (such as numberOfPizzaSlicesEaten or welcomeMessage) with a value of a particular type (such as the number 4 or the string "Hello"). The value of a constant can’t be changed once it’s set.

Constants must be declared before they’re used. You declare constants with the let keyword:

let numberOfPizzaSlicesEaten = 8

This code can be read as: "Declare a new constant called numberOfPizzaSlicesEaten, and give it a value of 8."

A note about naming: You can name constants anything you like, with a few small restrictions. The biggest one to remember is that constant names can’t start with a number (though they can contain a number elsewhere). The names you choose for your constants are important. Writing code that is easy for you (and other humans) to read and understand is a vital part of being a good programmer. So choose names that are concise but very clearly convey the purpose of a constant. You should avoid the temptation to abbreviate names. An example of a poorly written constant:

let numberOfZaSlicesEaten = 8

You may understand that "Za" means "Pizza" - however, it may be difficult for another person reviewing your code to understand the reference. Also, no self-respecting person uses "za." 🍕

Learn to use variables (var) to store and change values

Like a constant, variables associate a name with a value of a particular type. Unlike a constant, variables can be given new values as the program runs. To create a variable, use a var statement.

Here’s an example of how constants and variables can be used to track the number of pizza slices a user has eaten:

let numberOfPizzaSlicesEaten = 8
var currentPizzaSlice = 2

In this example, the maximum number of allowed pizza slices to be eaten is declared as a constant, because the maximum value never changes. The current pizza slice counter is declared as a variable, because this value must be incremented after each slice is eaten.

Learn when to use var vs let

Rule of thumb: If you have a value that needs to change, you should use a variable. If you have a value that never changes, use a constant.

You might think that always using variables makes sense, because you can change them if you need to, or leave them the same. In fact, many languages don’t have constants, and only use variables. However, this is not a good idea in practice.

In fact, as you read and write more and more Swift you’ll notice that variables are actually quite rarely used. As a rule of thumb, you should always make your values constants with let. If, and only if, you actually need a value that can change, should you change your value to a variable.

If you have a value that needs to change, you should use a variable. If you have a value that never changes, use a constant.

Learn to use different types of variables and constants, including Int, Float, Bool, etc.

Normally, Swift is able to figure out, or infer the type of a value based on context. It’s clear that 42 is an integer, or Int, not a string. Similarly, “Hello” is obviously not a number, it’s a String. This feature is called type inference and is one of the things that makes Swift concise and nice to write.

You can provide a type annotation when you declare a constant or variable, to be clear about the kind of values the constant or variable can store. Write a type annotation by placing a colon after the constant or variable name, followed by a space, followed by the name of the type to use.

String

This example provides a type annotation for a variable called typeOfPizzaEaten, to indicate that the variable can store String values:

var typeOfPizzaEaten: String = "margherita"

The colon in the declaration means “…of type…,” so the code above can be read as: “Declare a variable called typeOfPizzaEaten that is of type String, and give it the value "margherita".”

The phrase “of type String” means “can store any String value.” Think of it as meaning “the type of thing” (or “the kind of thing”) that can be stored.

Number Types

There are actually multiple number types, including Int, UInt, Float, and Double. Int is short for integer and is a whole number that can be either positive or negative. UInt is an unsigned integer, and is a whole number but it can only be positive. In other words, it can’t have a minus sign. You’ll see both types used in Swift, but Int is more common, and is the default. Float and Double are both kinds of floating point numbers.

Floating point numbers are numbers with a decimal point like 3.14. The difference between Float and Double is their precision, and the maximum value they can store. Double is more precise and can store larger numbers than a Float. However, it also takes up twice as much memory space as a Float. You’ll see both types used in Swift, but Double is more common, and is the default.

Alt Text

Boolean

Another common type is Bool, which is short for boolean. Boolean values can only be either true or false. We could create a boolean variable like so:

let pizzaIsAwesome = true

Challenge

Let's put our knowledge of constants, variables, and type annotations together, and see if we can complete the Challenge:

Create variables and constants for various parts about you, such as your name, your hometown, your favorite color and food, and anything else you think someone would be interested to know about you. Think about which of these should be variables, and which should be constants. Try to come up with at least 8 constants and variables in total.

Print each of these using print() statements and inserting the variable or constant in the parentheses.

Give it a shot before scrolling down! 😉

var myAge: UInt = 78 
let myFavoriteColor: String = "Aquamarine Blue"
let myFavoriteFood: String = "Sushi"
let firstName: String = "Arthur"
let lastName: String = "Curry"
let birthYear: Int = 1941
let homeTown: String = "Atlantis"
let university: String = "School of Hard Knocks"
let occupation: String = "Lighthouse Keeper"

print(firstName)
print(lastName)
print(birthYear)
print(myFavoriteFood)
print(myFavoriteColor)
print(homeTown)
print(university)
print(occupation)

Bonus Challenge

Now it's your turn!

Create a constant called introduction. This should be a readable sentence or paragraph that includes all of the constants and variables you made and combines them into a single string.

Hints: Look up string interpolation in Swift to learn how to turn variables into text. Google is your friend here. 😉

Note: We will cover string interpolation in detail in a later lesson, so don't worry if you don't already know it, or find it confusing at first.

Like this post?

You can find more by following me on twitter 😄: @joshuarutkowski

Thanks for reading!

Discussion (0)