Value-Binding in Swift

They call this a pattern

Image for post
Image for post
Photo by Helena Lopes on Unsplash

Value binding with Tuples? Let’s go!

Shall we get started, then?

Difficulty: Beginner | Easy | Normal | Challenging

Prerequisites:

  • Coding in Swift Playgrounds (guide HERE)

Terminology

Tuple: A way in Swift to allow you to store multiple values in a single variable

Value-Binding: A pattern that matches values to variables or constant names

Value-binding binds matched values to a variable or constant name.

In practice this means that we can bind a value to a constant (which is a let) or a variable (which is a var).

Our example Tuple; names matched to ages for three people (don’t worry, you don’t know them):

let nameAgeTuples = [(24, "Dave"), (32, "Tarik"), (24, "Emily")]

We move through each of the values in the tuple, and if (and only if) the name matches Dave the age will be printed:

for tuple in nameAgeTuples {
switch tuple {
case (_, "Dave"):
print(tuple.0)
default:
print("Didn't match")
}
}

As you can see, a wildcard underscore _ is used for the age, as in this case we aren’t interested in giving that parameter a name.

for tuple in nameAgeTuples {
switch tuple {
case (24, let name):
print(name)
default:
print("Didn't match")
}
}

Here we are value binding the name to, well the variable called name.

It should be remembered that value binding is a temporary binding, and will only exist as long as the case does.

Conclusion:

Value Binding is a great way of naming values in Switch statement temporarily.

Another tool in your toolkit? Yes, yes it is.

Enjoy coding!

The Twitter contact:

Any questions? You can get in touch with me HERE

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store