Where “where” may be used?

This is by far the most faved/retweeted Swift tip of mine lately:

indeed cool, unexpected and forgettable feature of Swift pattern-matching.

The fact is you can use where keyword in a case label of a switch statement, a catch clause of a do statement, or in the case condition of an if, while, guard, for-in statement, or to define type constraints.

for-in

func checkForIn(array: [Int], dict: [Int: String]) {  
for num in array where dict[num] != nil {
// 1, 2
}
}
checkForIn([1,2,3,4], dict: [1:"one", 2:"two"])

do-catch

enum MyError: ErrorType {  
case Oooggh(String)
}
func errorProne() throws {  
throw MyError.Oooggh("nope")
}
do {  
try errorProne()
} catch MyError.Oooggh(let argument) where argument == "agree" {
// not match "agree" != "nope"
} catch MyError.Oooggh(let argument) where argument == "nope" {
// match "nope"
}

while

func checkWhile(inout array: [Int]?) {  
while let arr = array where arr.count < 5 {
array?.append(0)
}
}
var mutableArray:[Int]? = []  
checkWhile(&mutableArray) // [0, 0, 0, 0, 0]

if

func checkIf(string: String?) {  
if let str = string where str == "checkmate" {
print("game over") // match
return
}
print("let's play")
}
checkIf("checkmate")

guard

func checkGuard(string: String?) {  
guard let str = string where str != "checkmate" else {
print("game over") // match
return
}
print("let's play")
}
checkGuard("checkmate")

switch-case

var value = (1,2)  
switch value {
case let (x, y) where x == 1:
// match 1
break
case let (x, y) where x / 5 == 1:
// not-match
break
    default:
break
}

type constraint

// generics
func genericFunction<S where S: StringLiteralConvertible>(string: S) {  
print(string)
}
genericFunction("lambada")

only pity, that where keyword is not really described in details by the “The Swift Programming Language` book.

anyway… now it’s clear. Gist code is here.

I did not mention it here, but where is used to define constraints for Generic functions.

Conclusion

Of course where is part of control flow of Swift program and may be used almost everywhere.

Find more on my blog.krzyzanowskim.com.