Swift Tutorial 1 – Getting Started with Swift and Variables

What is Swift?

Swift is a relatively new programming language created by Apple and used for iOS, Mac OS X, tvOS, and watchOS apps. Back in 2014, Apple announced the first version of Swift at WWDC. Apple claimed Swift was “Objective-C without the C” and it’s done a very good job at doing that. For those readers that know about C, C++, or Objective-C, they also know that dealing with such a powerful language can be tedious, especially with memory management. But Swift’s syntax and ease-of-use make it a great language to pick up and use for your future apps!

Learn iOS by building real apps

Check out The Complete iOS Development Course – Build 14 Apps with Swift 2 on Zenva Academy to learn Swift 2 and iOS development from the ground-up with an expert trainer.


FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

Installing Xcode

Before get into Swift, we need to install all of the tools that will allow us to build Swift apps. We’ll be learning Swift through Apple’s official development IDE Xcode. You need a computer running the latest version of of OS X. Xcode isn’t available for Windows or Linux computers. Open up the Mac App Store and search for Xcode. It should be the first search result listed under “Developer Tools” and marked with the Essentials tag. Make sure the publisher is Apple and go ahead and download Xcode. It’s a pretty big app, but it comes with everything we’ll need to start learning Swift, as well as developing iOS, OS X, tvOS, and watchOS apps. After it downloads and installs, open up Xcode and we should be greeted with a menu that looks like the below image.

Intro to Swift 1 - 1

Instead of creating a project, we’re going to use a new Xcode feature that will allow us to see the results of our Swift code directly and in real time. This is called Playgrounds. They allow us to type in our Swift code and immediately see the results on the right pane. Select the very first option “Get started with a playground” and give it a name in the window that pops up. The platform doesn’t really matter, but we’ll leave it as iOS. Click next and choose a folder for our playground. Click finish and a new window like the following should pop up.

Intro to Swift 1 - 2

This is the playground! Notice how it’s split up into the larger left pane and the smaller right pane. The left pane is where we’ll type all of our Swift code, and the right pane will show the results of typing that Swift code. In fact, it’s already generated us a nice Hello World-style program! Now that Xcode is installed and we have a playground file configured, we can get started learning Swift!

Variables and Constants

A variable is the way we store information in a program. They’re somewhat similar to the variables you might have encountered in your math class: a value with an associated name. That’s really what Swift variables are. When declaring a variable, your computer or phone or system (in a more generic sense) will set aside some of your RAM to hold your variable’s value. We give variables a name so that we don’t have to use a long memory address; we can just use x or y or numberOfDogs to refer to that value. A constant is a variable that is immutable, or whose value can’t be changed.

In Swift, we can declare variables by using the var keyword, followed by the variable name, an equals sign, and the value we want to give to that variable. Look at our example line that Xcode automatically generated for us:

var str = "Hello, playground"

First comes the var  keyword, then the name of the variable (str  in this case), then an equals sign, and finally the value of the variable (Hello, playground ). This kind of value is called a String and we’ll be learning more about those later on. We can declare constants in a similar fashion, except we use let  instead of var :

let PI = 3.1415926

This declares a constant whose value we can’t reassign with the equals sign later on in our program. Notice how one of the variables was a String and this other is a decimal number. We didn’t have to explicitly tell Swift the type of the variables. However, there is a way to explicitly declare the type of a variable in Swift. Before the equals sign, put a colon and the variable type like this: var value: Double = 3 . This explicitly tells Swift that the variable is a double, even though the value looks like an integer.

Variable Types and Inference

But what is a double or an integer? In Swift, we have many different number types, but we’ll look at the most common ones. The first represents an integer, which is a positive or negative whole number with no decimal part. Integers can be signed, meaning they can be either positive, negative, or zero, or they can be unsigned, meaning they can only be positive or zero. We can denote a signed integer by the type Int  and an unsigned integer by UInt. Both of these values have upper and lower bounds, so they’re not pure mathematical integers, since computer memory is limited. We can get these upper and lower bounds by typing Int.max  and Int.min  into our playground. This also works for all of the number types we’ll discuss.

In addition to integers, we also have a Swift type analogous to mathematical real numbers, or numbers with decimal components. (These are also called “floating-point numbers since the decimal point can “float”) We have Float  and Double , but we’ll be using Double  more often. Let me explain why. Like I mentioned earlier, we didn’t have to explicitly state the type of a Swift variable because the type is inferred. This means that depending on the value, Swift will make an assumption on what the type of the variable should be so we don’t have to state the type. Suppose we had variables like the following:

var x = 163953
var y = 351.452
var z = 143 + 1.34

Swift will assume anything without a decimal part is an Int  and anything with a decimal part a Double . Note how the third variable is the sum of an integer and a real number. This outputs a number with a decimal part, hence it is promoted to a Double . These aren’t the only ways to denote those numbers, however. For longer numbers, Swift will allow us to use leading zeros or the underscore (_) to break up large numbers like the following var billion = 1_000_000_000 .

We have another type that represents true and falseness called the boolean. The only two boolean values are true and false. We can declare boolean variables in the same way we can declare other variables: var lightsAreOn = true . We’ll see more of these when we talk about control flow, but it’s a good knowledge to have at the moment.

Type Conversions

We’ve seen how Swift can infer the type of a sum of an integer and a real number, but what if we wanted to get an integer back? Swift will allow us to convert between integers and floating-point values in a very simple way. We simply write the name of the type and have a set of parentheses. What goes in the parentheses is the variable we want to convert. Let’s look at an example.

let E = 2.71828
let intE = Int(E)

In the above example, we declared a constant to represent Euler’s number, but we also have an integer constant that represent it as well. If you type that into the playground, notice that the integer value of that is actually 2, and not 3. This is because converting a floating-point number into an integer truncates the decimal part; it does not round.

Type Aliasing

We’ve already talked about the various types we have in Swift. However, if you’re building an app that helps users analyze how their disk storage is being used up. When you’re coding, you’ll probably have a lot of unsigned integers to account for things like the file size. However, instead of dealing with unsigned integers, it might be appropriate, given the context, to redefine the unsigned integer type to be a new type. With type aliasing, we can do exactly this.

typealias FileSize = UInt
var largestFile = FileSize.max

The first line declares a new alias to the existing UInt  type. Afterwards, we can use it just like we would UInt , but it looks more appropriate, contextually. This is a trivial example, but we can type alias more complicated type to make our code easier to understand.


Suppose we were representing a list of files and their file sizes since we want to build that disk storage app. We could declare two separate variables for each file, but that would be too many variables! Instead, we can group them in structures called tuples. They are a way to group many values of different types into a single variable. Let’s look at how we can declare and use them.

let largestFile = (FileSize.max, "reallyBigFile.txt")
let (fileSize, fileName) = largestFile

let (onlyTheFileSize, _) = largestFile

We can simply declare the tuple between parentheses with the comma-separated values. The second line shows how we can decompose a tuple into separate constants, and subsequent lines print out the result. In some cases, we only want some of the tuple’s values. We can omit parts of the tuple by using the underscore in place of the variable name when decomposing the tuple.

Instead of making even more variables, we can access the tuple’s elements directly. They’re zero-indexed values corresponding to the location of the value in the tuple. We can make tuples even easier to use by assigning the values names! Now, instead of using some arbitrary index, we can actually use those names like the following.


let secondLargestFile = (fileSize: FileSize.max - 1, fileName: "secondLargestFile.txt")

To recap, tuples are a way we can store multiple values into a single variable. We can decompose the tuple into separate constants or variables, or we can access the tuple’s contents directly through indices or named values.


Suppose we had a user-entered string we wanted to convert to an integer. We can convert “19375” to an integer pretty easily, but not “Hello, playground”. Swift has a way to handle this through a structure called an optional. An optional says either that a specific value exists and it is this, or that no value exists. To declare an optional, we need to explicitly declare the type and put a question mark after the type. Let’s see how we can achieve this.

var maybeANumber = "19375"
var number:Int? = Int(maybeANumber)

We see on the right pane that the correct value is displayed. Now try changing the String to include a letter. The value then changes to nil , meaning that it has no value.

Suppose we’re given an optional to print out, but we don’t know if it has a value or not. If it does, then we want to force Swift to print it out. This is called forced unwrapping. Let’s see it in action.

if number != nil {

We’ll talk more about if-then statements when we talk about control flow, but just know that the if statement is checking whether or there is a value in the optional, and, if there is, it is printing it out. Normally, we can’t just print out the value if it’s an optional, but we can force Swift to using forced unwrapping. We simply put an exclamation point after the variable name and that tells Swift “I know for a fact that this optional has a value so please use it.”

There’s another technique technique we can apply to this scenario called optional binding. What we do is we bind the value of the optional to a constant if the value exists. Let’s see this technique in action.

if let convertedNum = Int(maybeANumber) {
} else {
    print("No value!")

This is saying that if our optional has a value, bind it to this constant so we can use it in the block. Try changing maybeANumber  to different values and see what the preview pane on the right outputs.

To review, optionals tell us either there exists a value and it is this, or there does not exist a value. We can use forced unwrapping to get the value of an optional if we know that the value exists. As a different technique, we can use optional binding to bind the value of that optional to a constant so we can use it later.