2015-01-13 34 views
-2

我無法訪問儲蓄目標函數中的變量incomeValue。 Xcode中給了我懸而未決的標識符‘incomeValue’的錯誤「使用。如何訪問Swift中的按鈕操作中的變量

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

}

+0

使其成爲變量 –

+1

在func中聲明變量限制了範圍 – ericgu

回答

1

你的問題是,你聲明incomeValueincomeSliderChanged(_:)函數內部,這限制了incomeValue範圍,該功能,這意味着你只能從withing開{和關閉的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)