Adam Rush

@Adam9Rush

22 November, 2021

An if statement is probably the most common statement used across programming in general. It’s not any different in Swift, and in fact, it is super readable.

let sports = ["🏉", "⚽️", "🏀", "🎾", "⛳️"]

if sports.contains("⚽️") {
    print("Your list of sports contains my favourite sport!")
}

Considering this example, we have an array of sports icons and if your list contains my favourite sport “⚽️” then print “Your list of sports contains my favourite sport!” to the console.

This condition is met, so your console will look like this:

Your list of sports contains my favourite sport!

If your code requires some logic if the condition is false, you can add an else to your statement.

let sports = ["🏉", "🏀", "🎾", "⛳️"]

if sports.contains("⚽️") {
    print("Your list of sports contains my favourite sport!")
} else {
    print("Your list of sports doesn't contain my favourite sport!")
}

In this example, you have removed my favourite sport as an example, and you will see that the else statement is hit.

It’s also possible to add additional else, but this time, you can add other conditions to the else statement.

let sports = ["🏉", "🏀", "🎾", "⛳️"]

if sports.contains("⚽️") {
    print("Your list of sports contains my favourite sport, Football!")
} else if sports.contains("🏀") {
    print("Your list of sports contains my 2nd favourite sport, Basketball!")
}

In this example, you have two conditions around the list of sports, and because we only have Basketball 🏀, the 2nd condition will be met.

Sponsor

Subscribe for curated Swift content for free

- weekly delivered.