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!" ...

Get Swift Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.