Custom tuple
In this chapter you saw how a tuple pattern could match a three-dimensional coordinate, (x, y, z). You can create a just-in-time tuple expression at the moment you’re ready to match it:
let name = "Bob" let age = 23
if case ("Bob", 23) = (name, age) {
print("Found the right Bob!") // Printed!
}
In this example, the name and age constants are combined into a tuple and are evaluated together.
Another such example involves a login form with a username and password field. The user might not fill all the fields out before clicking Submit. In this case, you’d want to show a specific error message to the user indicating which field is missing.
var username: String? var password: String?
switch (username, password) { case let (username?, password?):
print("Success!") case let (username?, nil):
print("Password is missing") case let (nil, password?):
print("Username is missing") case (nil, nil):
print("Both username and password are missing") // Printed!
}
Each case checks of one of the possible submissions. You write the success case first because if it is true, there is no need to check the rest of the cases. switch statements in Swift do not fall through, so if the first case condition is true, the rest of the conditions will not be evaluated.