使用 Swift 的预期声明错误 [英] Expected Declaration Error using Swift
问题描述
我正在尝试使用 NSUserDefaults
将 UISwitch
的布尔值传递给另一个类.出于某种原因,在包含开关的类中,应该将值设置为 NSUserDefaults
的 if
语句无法读取开关声明.
I'm trying to pass the boolean value of a UISwitch
to another class using NSUserDefaults
. For some reason, in the class that contains the switches, the if
statements that are supposed to set the value to NSUserDefaults
cannot read the switch declarations.
@IBOutlet var shrimpSwitch: UISwitch!
@IBOutlet var nutSwitch: UISwitch!
@IBOutlet var dairySwitch: UISwitch!
let switchState = NSUserDefaults.standardUserDefaults()
if shrimpSwitch.switch.on{
switchState.setBool(true, forKey: "shrimpSwitch")
}
else{
switchState.setBool(false, forKey: "shrimpSwitch")
}
if nutSwitch.on{
switchState.setBool(true, forKey: "nutSwitch")
}
else{
switchState.setBool(false, forKey: "nutSwitch")
}
if dairySwitch.on{
switchState.setBool(true, forKey: "dairySwitch")
}
else{
switchState.setBool(false, forKey: "dairySwitch")
}
在第一个 If 语句(shrimpSwitch.on)中,它会说预期的声明.我是否宣布所有开关都错了?任何帮助,将不胜感激.谢谢
In the first If statement(shrimpSwitch.on), it will say Expected Declaration. Am I declaring the switches all wrong? Any help would be appreciated. Thanks
推荐答案
问题是您需要将代码放在方法中.您只需将其移动到 viewDidLoad() 或任何其他方法.
The problem is that you need to put your code inside a method. All you need is to move it to viewDidLoad() or any other method.
这篇关于使用 Swift 的预期声明错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!