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

时间:2015-01-13 04:45:20

标签: ios xcode 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)
}

}

1 个答案:

答案 0 :(得分:1)

您的问题是您在incomeValue功能中声明了incomeSliderChanged(_:)。这会将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)
}

如果您不熟悉编程,我建议您阅读Scope的概念:http://en.wikipedia.org/wiki/Scope_(computer_science)