Qualifying with where

You can specify a where condition to further filter a match by checking a unary condition in line. In Chapter 5, “Advanced Control Flow” you saw an example like this:

for number in 1...9 { switch number {

case let x where x % 2 == 0: print("even") // 4 times

default:

print("odd") // 5 times

}

}

If the number in the code above is divisible evenly by two, the first case is matched.

You can utilize where in a more sophisticated way with enumerations. Imagine you’re writing a game where you want to save the player’s progress for each level:

enum LevelStatus { case complete

case inProgress(percent: Double) case notStarted

}

let levels: [LevelStatus] = [.complete, .inProgress(percent: 0.9), .notStarted]

for level in levels { switch level {

case .inProgress(let percent) where percent > 0.8 : print("Almost there!")

case .inProgress(let percent) where percent > 0.5 : print("Halfway there!")

case .inProgress(let percent) where percent > 0.2 : print("Made it through the beginning!")

default: break

}

}

In this code, one level in the game is currently in progress. That level matches the first case as 90% complete and prints "Almost there!".

results matching ""

    No results matching ""