user7024499
user7024499

Reputation: 961

Using Switch Statements in Swift - Value binding INSIDE the parentheses vs outside?

I'm wondering what in the world the difference is between these two following examples. If there is no difference, simply say no difference, and I'll give the answer to you. Notice in case two, the let value binding is declared INSIDE the parenthesis of the tuple pattern, whereas in case one, the let is declared outside of the tuple. When I play around with both of these examples, they both yield the exact same results. Thanks.

Case 1)

let myNumbers = (1, 2)
switch myNumbers {
   case let (x, 2):
      print("the value of x is \(x)")
   default:
      print("n/a")
}

Case 2)

let myNumbers = (1, 2)
 switch myNumbers {
    case (let x, 2):
       print("the value of x is \(x)")
    default:
       print("n/a")
 }

Upvotes: 1

Views: 638

Answers (1)

Alexander
Alexander

Reputation: 63271

Case 1 is more concise, and better suited for the general case.

Case 2 is more granular. Consider this case:

switch myNumbers {
    case (let x, var y):
        // x is a constant, y is mutable.
        print("the value of x is \(x)")
    default:
        print("n/a")
}

Upvotes: 2

Related Questions