4.2. If-else statements

if-else statements allow us to specify what should happen if a condition is true or false. So, now we can add a code block if the condition is false. We can modify our previous example to print "It is not 5!", if myNum is not 5.

if myNum == 5 {
    print("It is 5!")
}else{
    print("It is not 5!")
}

You can build a if-else if-else chain if we are handling multiple true conditions. For example, the following code prints myNum if myNum is 1, 3, or 5. Else it prints "Not 1, 3, or 5!"

//if-else-if-else chain ...
if myNum == 1 {
    print("It is \(myNum)!")
}else if myNum == 3{
    print("It is \(myNum)!")
}else if myNum == 5{
    print("It is \(myNum)!")
}else{
    print("Not 1, 3, or 5!")
}

Here, the conditions are checked sequentially for each if and else if. If none of the conditions are true, the program switches to the else block.

Last updated

Was this helpful?