即使我在 Swift、Xcode 6 中声明,也会切换“预期声明”错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26643222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:03:01  来源:igfitidea点击:

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

xcodeswiftswitch-statementdeclarationxcode6.1

提问by Ben Oneill

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

我在 switch 语句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)"
}

回答by Steve Rosenberg

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.

案例必须详尽无遗,否则您必须有一个默认声明。我修改了 case 0: 只是为了让它在操场上执行。

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