user2988464
user2988464

Reputation: 3471

Swift: unresolved identifier from a switch statement

I'm trying the following in the playground in Xcode6-Beta4, following the apple's swift tour:

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."
}

then I try to call the variable vegetableComment defined inside the switch statement, I got an error of Use of unresolved identifier 'vegetableComment'

Is it something relating the the scope / closure of switch statement in swift?

Upvotes: 1

Views: 1881

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

Is it something relating the the scope / closure of switch statement in swift?

Yes, it is related to the scope of variables. You have four constants called vegetableComment. Each one is scoped to its case of the switch statement.

In order to access a variable that you assign inside a switch, you need to declare it as a var before entering the switch:

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

Upvotes: 7

Related Questions