andrewz
andrewz

Reputation: 5220

Is there a way to access the unmatched value in a switch statement?

I want to access the value used in the switch statement in the default clause without first creating a temporary local var for the value, for example:

switch i + 5 {
    case 2: // ...
    case 7: // ...
    default:
      print("\(switchValue)") 
}

Is there such a thing as, for example, a newValue in the didSet property clause?

Upvotes: 0

Views: 131

Answers (1)

Alexander
Alexander

Reputation: 63167

You can conditionally bind to a variable, with no condition (so it acts like case _ or default

let i = 123

switch i + 5 {
    case 2: break // ...
    case 7: break // ...
    case let switchValue:
        print("\(switchValue)") 
}

To be fair, you probably shouldn't do this.

Upvotes: 3

Related Questions