do it better
do it better

Reputation: 4807

case and switch in swift

in the code shown below vegetable declared many times as a constant. But Xcode didn't get an error. Why Xcode successfully compiled it and didn't get and error? Let is a constant.?

let​ ​vegetable​ = ​"red pepper"
​switch​ ​vegetable​ {
​case​ ​"celery"​:
​    ​let​ ​vegetableComment​ = ​"Add some raisins and make ants on a log."
​case​ ​"cucumber"​, ​"watercress"​:
​    ​let​ ​vegetableComment​ = ​"That would make a good tea sandwich."
​case​ ​let​ ​x​ ​where​ ​x​.​hasSuffix​(​"pepper"​):
​    ​let​ ​vegetableComment​ = ​"Is it a spicy ​\(​x​)​?"
​default​:
​    ​let​ ​vegetableComment​ = ​"Everything tastes good in soup."
​}

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks.

Upvotes: 0

Views: 1741

Answers (1)

cjwirth
cjwirth

Reputation: 2013

I assume you're actually talking about vegetableComment being defined as a constant, and that is what you are confused about.

In Swift, each case: block in a switch statement has its own lexical scope. That means that you can name all your variables the same in each of them, and they won't conflict. Almost as if they were in different functions.

On the same note, you can't access the variables in other. Here's some examples:

let​ ​vegetable​ = ​"red pepper"
var comment = ""
​switch​ ​vegetable​ {
​case​ ​"celery"​:
​    ​comment​ = ​"Add some raisins and make ants on a log."
    // This is only defined here
    var favoriteVegetable = "celery"

​case​ ​"cucumber"​, ​"watercress"​:
​    ​comment​ = ​"That would make a good tea sandwich."
    // This will be an error, because `favoriteVegetable` is only valid inside the celery case block
    // favoriteVegetable = "either cucumber or watercress"

​case​ ​let​ ​x​ ​where​ ​x​.​hasSuffix​(​"pepper"​):
​    ​comment​ = ​"Is it a spicy ​\(​x​)​?"

    // We can redefine favoriteVegetable here, because it has nothing to do with the one in the celery block
    let favoriteVegetable = "a pepper"

​default​:
​    ​comment​ = ​"Everything tastes good in soup."
​}

// Similarly, we can't access `favoriteVegetable` here
// println(favoriteVegetable)

// This was defined before the switch statement, so we can get the value that was calculated
println(comment)

Upvotes: 3

Related Questions