What is a "binding" in a Switch statement?

I'm following a Swift tutorial book in which the author lists the following code:

“switch number {
case let x where x % 2 == 0:

Regarding this code, the author then states:

“In the previous example, the binding introduced an unnecessary constant x; it’s simply another name for number.”

Could someone please let me know what the word "binding" means here? I tried searching online to no avail and I'm a bit confused now as to the actual meaning of this word in this context. Please help. Thank you!

The "let x = ..." is the binding. You're introducing a local constant called "x" which is bound to the value "number % 2 "(i.e., either 1 or 0), and would only be available in the body of the case block .

Actually, I misspoke a bit. "x" is bound to "number" if "number % 2" is = 0. Since you don't use "x" in the case body, it's really unnecessary.

1 Like

Thank you!

FYI: Swift now has isMultiply(of:) to test for even or odd: https://github.com/apple/swift-evolution/blob/master/proposals/0225-binaryinteger-iseven-isodd-ismultiple.md

if number.isMultiple(of: 2) ...

1 Like

Good to know, thank you!

Terms of Service

Privacy Policy

Cookie Policy