Home > Articles > Programming > General Programming/Other Languages

  • Print
  • + Share This
This chapter is from the book

else if

The else if conditional lets you chain multiple conditional statements together. else if allows you to check against multiple cases and conditionally executes code depending on which clause evaluates to true. You can have as many else if clauses as you want. Only one condition will match.

To make your code a little easier to read, extract the nested if/else statement to be a standalone clause that evaluates whether your town is of medium size.

Listing 3.6 Using else if

import Cocoa

var population: Int = 5422
var message: String
var hasPostOffice: Bool = true

if population < 10000 {
    message = "\(population) is a small town!"
} else if population >= 10000 && population < 50000 {
    message = "\(population) is a medium town!"
}  else {
    if population >= 10000 && population < 50000 {
        message = "\(population) is a medium town!"
    } else {
        message = "\(population) is pretty big!"
    }
    message = "\(population) is pretty big!"
}

print(message)

if !hasPostOffice {
    print("Where do we buy stamps?")
}

You are using one else if clause, but you could have chained many more. This block of code is an improvement over the nested if/else above. If you find yourself with lots of if/else statements, you may want to use another mechanism, such as switch described in Chapter 5. Stay tuned.

  • + Share This
  • 🔖 Save To Your Account