Value-Binding Pattern
This is the very same as binding values to variables via let or var.
Only in a switch statement. You've already seen this before, so I'll
provide a very short example:
switch (4, 5) {
case let (x, y): print(\"\(x) \(y)\")
}
The let (x, y) in the example above will take the values of our (4, 5) tuple and write them into two new variables named x and y.
We can easily combine this with the other pattern matching operations to develop very powerful patterns. Imagine you have a function that returns an optional tuple (username: String, password: String)?. You'd like to match it and make sure if the password is correct:
First, our fantastic function (just a prototype):
func usernameAndPassword()
-> (username: String, password: String)? {... }
Now, the switch example:
switch usernameAndPassword() {
case let (_, password)? where password == \"12345\": login()
default: logout()
}
See how we combined multiple Swift features here, we will go through them step by step:
- We use
case letto create new variables - We use the
?operator to only match if the optional return value from theusernameAndPasswordfunction is not empty. - We ignore the
usernamepart via_, because we're only interested in thepassword - We use
whereto make sure our highly secure password is correct - We use
defaultfor all the other cases that fail.
