如何在 Swift 中的按钮操作中访问变量

How do I access a variable in a button action in Swift

我无法访问 savingsGoal 函数中的变量 incomeValue。 Xcode 给我错误“使用未解析的标识符 'incomeValue'。

@IBAction func incomeSliderChanged(sender: UISlider) {
    var incomeValue = Double(sender.value)
    currentIncomeLabel.text = ("$\(incomeValue) /yr")
}
@IBAction func savingsSliderChanged(sender: UISlider) {
    var savingsValue = Int(sender.value)
    savingsLabel.text = ("\(savingsValue)% of income")

    println("savings value \(savingsValue)%")
}
@IBAction func indexChanged(sender: UISegmentedControl) {
    switch sender.selectedSegmentIndex {
    case 0:
        println("first segement clicked")
    case 1:
        println("second segment clicked")
    default:
        break;
    }
}
@IBAction func calculateButtonPressed(sender: AnyObject) {
}


func savingsGoal () {
    var futureIncome = incomeValue + (incomeValue * 3.8)
}

}

您的问题是您在 incomeSliderChanged(_:) 函数中声明了 incomeValue。这将 incomeValue 的范围限制为该函数,这意味着您只能从 incomeSliderChange(_:) 的开始 { 和结束 } 中引用它。要解决此问题,请在函数外声明您的 incomeValue 变量。

var incomeValue: Double = 0.0 // You can replace 0.0 with the default value of your slider

@IBAction func incomeSliderChanged(sender: UISlider) {
    // Make sure you get rid of the var keyword.
    // The use of var inside this function would create a 
    // second incomeValue variable with its scope limited to this function
    // (if you were to do this you could reference the other incomeValue
    // variable with self.incomeValue).
    incomeValue = Double(sender.value)
    currentIncomeLabel.text = ("$\(incomeValue) /yr")
}

func savingsGoal() {
    // You can now access incomeValue within your savingsGoal() function
    var futureIncome = incomeValue + (incomeValue * 3.8)
}

如果您是编程新手,我建议您阅读范围的概念:http://en.wikipedia.org/wiki/Scope_(computer_science)