Value-binding pattern

The value-binding pattern sounds more sophisticated than it turns out to be in practice. You simply use var or let to declare a variable or a constant while

matching a pattern. You can then use the value of the variable or constant inside the execution block:

if case (let x, 0, 0) = coordinate {

print("On the x-axis at (x)") // Printed: 1

}

The pattern in this case condition matches any value on the x-axis, and then binds its x component to the constant named x for use in the execution block.

If you wanted to bind multiple values, you could write let multiple times or, even better, move the let outside the tuple:

if case let (x, y, 0) = coordinate {

print("On the x-y plane at ((x), (y))") // Printed: 1, 0

}

By putting the let on the outside of the tuple, the compiler will bind all the unknown constant names it finds.

results matching ""

    No results matching ""