Search code examples
xcodeswiftswitch-statementdeclarationxcode6.1

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

Solution

  • 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
         }
    }