No history yet

Introduction to Swift

The Building Blocks

Swift is the modern programming language used to build apps for all of Apple's platforms. It's designed to be safe, fast, and easy to read. Let's start with the most basic concept: storing information.

In programming, we store data in containers called variables and constants. Think of them as labeled boxes where you can put things. A variable is a box whose contents you can change, while a constant is a box that, once filled, cannot be changed.

variable

noun

A storage location paired with an associated symbolic name, which contains some known or unknown quantity of information referred to as a value. The value can be changed.

We use the keyword var to declare a variable.

constant

noun

A value that cannot be altered by the program during normal execution. It is fixed.

We use the keyword let to declare a constant. It's good practice to prefer constants over variables unless you specifically need to change the value later. This makes your code safer and easier to understand.

// A constant for a value that won't change.
let pi = 3.14159

// A variable for a value that might change.
var currentScore = 0

// We can change the variable's value.
currentScore = 10

// This would cause an error, because 'pi' is a constant.
// pi = 3.14

Types of Data

Swift needs to know what kind of data you plan to store. Is it a whole number, a decimal, text, or a simple yes/no value? This is a core feature called type safety, which helps prevent errors by ensuring you don't, for example, try to do math with a piece of text.

The most common data types you'll use are:

TypeDescriptionExample
IntInteger, a whole number.42, -100
DoubleA number with a fractional component.3.14, -0.5
StringA sequence of characters, used for text."Hello, world!"
BoolA Boolean value, either true or false.true

Swift is smart enough to figure out the data type on its own from the value you provide. This is called type inference.

let city = "New York"      // Swift infers this is a String
let population = 8400000   // Swift infers this is an Int
let isCapital = false      // Swift infers this is a Bool
let latitude = 40.7128    // Swift infers this is a Double

You can also be explicit about the type if you need to be, by adding a colon and the type name.

var temperature: Double = 72.5

A particularly useful feature with strings is interpolation, which is a clean way to build a new string from variables and constants.

let name = "Alex"
let age = 32
let greeting = "My name is \(name) and I am \(age) years old."
// The value of 'greeting' is "My name is Alex and I am 32 years old."

Controlling the Flow

Programs rarely run straight from top to bottom. They need to make decisions and repeat actions. This is called control flow.

To make a decision, we use if, else if, and else statements. They check if a condition is true and run a block of code accordingly.

let userAge = 19

if userAge >= 18 {
    print("You are eligible to vote.")
} else {
    print("You are not yet eligible to vote.")
}

When you need to repeat a task, you use a loop. A for-in loop is perfect for running a piece of code for each item in a collection, or for a specific number of times.

// Loop 5 times
for i in 1...5 {
    print("This is loop number \(i).")
}

Packaging Code with Functions

As your programs grow, you'll find yourself writing the same lines of code over and over. Functions let you package up a piece of code, give it a name, and run it whenever you need it. This makes your code more organized and reusable.

You define a function using the func keyword, followed by the function's name and parentheses.

// Defines a simple function
func greetUser() {
    print("Welcome to the app!")
}

// Calls the function to execute its code
greetUser()

Functions become even more powerful when you can give them data to work with. These pieces of data are called parameters. You can also have the function give data back when it's done, which is called a return value.

// This function accepts a String as a parameter.
// It doesn't return a value.
func sayHello(to name: String) {
    print("Hello, \(name)!")
}

sayHello(to: "Maria") // Prints "Hello, Maria!"

// This function accepts two Ints as parameters.
// It returns an Int (indicated by -> Int).
func add(_ a: Int, to b: Int) -> Int {
    return a + b
}

let sum = add(5, to: 10) // 'sum' is now 15

Notice the labels in the function calls: to: "Maria" and to: 10. Swift uses parameter labels to make code read more like a natural sentence.

Time to check what you've learned.

Quiz Questions 1/5

In Swift, what is the keyword used to declare a value that will not change after it's first assigned?

Quiz Questions 2/5

Which of the following lines of Swift code contains an error?

These are the fundamental building blocks of the Swift language. With variables, data types, control flow, and functions, you have the tools to start writing simple but powerful programs.