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.