What is the utility of an else statement?


Hello, total Swift beginner here...

I'm just wondering what the purpose of an else statement is, if you can simply write some code to be executed (as in the example above) if your if statement is evaluated as false?

Sorry if this is a silly question.

It is perfectly true that there is often more than one way to write something in code. Sometimes, choosing how to write a function might come down to personal preference. In other cases, else will perhaps be the only way to do what you need (without jumping through a lot of hoops).

Here's a fabricated example I just thought up:

func addEvensSubtractOdds(_ numbers: [Int]) -> Int {
    var total = 0

    for number in numbers {
        if number.isMultiple(of: 2) { // if number is even
            total += number // add it
        } else { // if it's odd
            total -= number // subtract it
        }
    }

    return total
}

In this example, it doesn't really make sense to write this is any other way. You have two different branches depending on some condition. The else is necessary because you don't want the subtraction to happen when the if statement's condition evaluates to true, only when it evaluates to false.

1 Like

Sometimes you use an else block to exclude it from execution when the condition is true. This is sometimes necessary when you don't return within the if block.

For example, the follow 2 snippets (one with and one without an else block) produce different results:

var x = 0

if true {
    x = 2
} else {
    x += 1 // skipped because the condition is true
}

print(x) // prints 2
var x = 0

if true {
    x = 2
}

x += 1 // not skipped because it's not in an else-block

print(x) // prints 3
1 Like

Thank you very much Benjamin! Greatly appreciated. This makes perfect sense.

Thank you very much! That makes complete sense. Much appreciated.

Terms of Service

Privacy Policy

Cookie Policy