我无法通过不同的函数接收变量. 我分配了: var ageDescription: String = String() 作为全局变量的类之外,以及2个ibactions @IBAction func ageChanged(sender: UISegmentedControl) { switch age.selectedSegmentIndex { c
我分配了:
var ageDescription: String = String()
作为全局变量的类之外,以及2个ibactions
@IBAction func ageChanged(sender: UISegmentedControl) {
switch age.selectedSegmentIndex {
case 0:
print("Under 18")
let ageDescription = "under 18"
case 1:
print("Over 18")
let ageDescription = "over 18"
case 2:
print("Strictly over 21")
let ageDescription = "strictly over 21"
default:
print("IDK")
}
}
@IBAction func saveButtonTapped(sender: UIButton) {
print(ageDescription)
}
我希望用户能够选择年龄选项,然后使用saveButton打印出结果.但似乎在saveButton被点击后,它打印出一个零.我相信它与变量ageDescription有关,但我不确定是什么问题.
您正在将值赋给函数内的新变量并尝试访问另一个函数中的全局变量,因此它对您来说是零.由于您已声明了一个全局变量,因此无需在ageChanged函数中声明另一个局部变量,只需访问全局变量即可.试试这个:
@IBAction func ageChanged(sender: UISegmentedControl) {
switch age.selectedSegmentIndex {
case 0:
print("Under 18")
ageDescription = "under 18"
case 1:
print("Over 18")
ageDescription = "over 18"
case 2:
print("Strictly over 21")
ageDescription = "strictly over 21"
default:
print("IDK")
}
}
