Swift: Switch body with multiple patterns cannot bind to a variable

In the official Swift Programming Language manual, this should say about the switch case: "... if the case contains several patterns that match the control expression, none of these patterns can contain constant or variable bindings."

What does this mean if you have multiple templates?

+4
source share
1 answer

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

It 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 also allowed:

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 error:

error: 'case' labels with multiple patterns cannot declare variables
+3
source

All Articles