Keith Knauber
Keith Knauber

Reputation: 802

Why does Swift allow non-constant switch labels?

I was encouraged at first by Swift, because finally you can write switch statements using strings, which means that dictionary-based code is now almost readable.

let kMyDictionaryKey1 = "one"  // use 'let' to declare constant dictionary key
let kMyDictionaryKey2 = "two"  // use 'let' to declare constant dictionary key

println( "hello world" );

if ( true )
{
    var dictionary = [kMyDictionaryKey1: 1, "two": 2, "three": 3]

    for val in dictionary.keys {
        switch val {
        case kMyDictionaryKey1:
            println( "yay switch on Key1" )
            break

        case kMyDictionaryKey2:
            println( "yay switch on Key2" )
            break

        default :
            println("world" )
            break
        } // end switch
    }
}

The above code works great.

However, I also notice that you can have variables as case labels. For example, you can declare

var kMyDictionaryKey1 = "one"

There have been situations where I've wanted to do this, but it also seems dangerous. It could lead to sloppy code, and duplicate switch labels. Most languages don't allow this, and duplicate labels are compile time errors.

Do any other languages allow variables for case labels?

Upvotes: 1

Views: 909

Answers (1)

Tim
Tim

Reputation: 14446

Switch statements are meant to be a more expressive form of what you might have previously used a long chain of if... else if... else if... statements, hence the ability to use variables, strings, and expressions in case statements.

You can have multiple case statements that have the same case, but the first matching case is always the one that is executed.

Also, in Swift there is no fall-through on switch statements, so using break statements is unnecessary.

var testVal = "one"

var result = 0

switch(testVal)
{
case "one":
    result = 1
case "one":
    result = 2
default:
    result = 3
}

result // the result is 1

Upvotes: 1

Related Questions