Boon
Boon

Reputation: 41510

Swift: Switch case with multiple patterns cannot bind to variable

In the official Swift Programming Language guide, it has this to say about switch case: "...if the case contains multiple patterns that match the control expression, none of those patterns can contain constant or variable bindings."

What does it mean by containing multiple patterns?

Upvotes: 4

Views: 3128

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

It means that case labels with multiple patterns cannot declare variables.

This is allowed:

let somePoint = (1, 1)
switch somePoint {
// Case with multiple patterns without binding
case (0, _),
     (_, 0):
    println("(\(somePoint.0), \(somePoint.1)) is on an axis")
default:
    println("(\(somePoint.0), \(somePoint.1)) is not of an axis")
}

This is allowed, too:

let somePoint = (1, 1)
switch somePoint {
// Case with single patterns with binding
case (0, let y):
    println("(0, \(y)) is on an axis")
case (let x, 0):
    println("(\(x), 0) is on an axis")
default:
    println("(\(somePoint.0), \(somePoint.1)) is not of an axis")
}

However, this is prohibited:

let somePoint = (1, 1)
switch somePoint {
// Case with multiple patterns that have bindings
case (0, let y),
     (let x, 0):
    println("(\(x), \(y)) is on an axis")
default:
    println("(\(somePoint.0), \(somePoint.1)) is not of an axis")
}

The above produces an error:

error: 'case' labels with multiple patterns cannot declare variables

Upvotes: 3

Related Questions