Ben Oneill
Ben Oneill

Reputation: 111

switch 'expected declaration' error even when i have declared in Swift, Xcode 6

I get an error saying "expected declaration" by the switch statement https://www.dropbox.com/s/3cjeo3sxg0zw431/Screen%20Shot%202014-10-30%20at%2001.01.48.png?dl=0

let questionSelected = Int(arc4random_uniform(1))


switch questionSelected{
case 0:
let x = "(question goes here)"
}

Upvotes: 0

Views: 10238

Answers (2)

Subathra D
Subathra D

Reputation: 399

check the 'questionSelected' variable scope and Switch statement scope are in the same level

Upvotes: -1

Steve Rosenberg
Steve Rosenberg

Reputation: 19514

The cases must be exhaustive otherwise you must have a default statement. I modified the case 0: just to get it to execute in a playground.

let questionSelected = Int(arc4random_uniform(1))


switch questionSelected{
case 0:
    let x = "(question goes here)"
default:
    break
}

Okay, went an extra step. This works. Hook up the label to a storyboard.

class ViewController: UIViewController {


    @IBOutlet weak var questionBox: UILabel!


    override func viewDidLoad() {
        super.viewDidLoad()

        let questionSelected = Int(arc4random_uniform(1))

        switch questionSelected{
        case 0:
            questionBox.text = "Does this work?"
        default:
            questionBox.text = "Does this work better?"
        }

    }
}

Second update:

func thisCodeMustBeInAFunction() {

     let questionSelected = Int(arc4random_uniform(1))

     switch questionSelected{
         case 1:
             questionBox.text = "(question goes here)"
         default:
             break
     }
}

Upvotes: 1

Related Questions