2017-01-05 22 views
0

我收到錯誤:
收到錯誤:「不能與類型的索引,下標類型的‘[雙]’值‘(任何) - >內部’」

「Cannot subscript a value of type ‘[Double]’ with an index of type ‘(Any) -> Int’」 on the following line of code:

tipPer = tipPercentages[index] 

這裏是我的代碼的其餘部分(包括錯誤路線):((抱歉可怕的格式/語法,我是新來的斯威夫特)!)

import UIKit 

class ViewController: UIViewController { 

    var tipPer: Int = 0 

    let defaults = UserDefaults.standard 

    @IBOutlet weak var tipLabel: UILabel! 
    @IBOutlet weak var totalLabel: UILabel! 
    @IBOutlet weak var perPersonLabel: UILabel! 
    @IBOutlet weak var billField: UITextField! 
    @IBOutlet weak var peopleField: UITextField! 
    @IBOutlet weak var tipControl: UISegmentedControl! 


    override func viewWillAppear(_ animated: Bool) { 
     super.viewWillAppear(animated) 

     // This is a good place to retrieve the default tip percentage from UserDefaults 
     // and use it to update the tip amount 
    } 

    override func viewDidLoad() { 

     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

    @IBAction func onTap(_ sender: AnyObject) { 

     view.endEditing(true) 
    } 


    @IBAction func calculateTip(_ sender: AnyObject) { 

     let tipPercentages = [0.10, 0.15, 0.20] 

     defaults.synchronize() 



     if (tipControl.selectedSegmentIndex == 0) { 
      let index = tipControl.selectedSegmentIndex 
     } 

     if (tipControl.selectedSegmentIndex == 1) { 
      let index = tipControl.selectedSegmentIndex 
     } 

     if (tipControl.selectedSegmentIndex == 2) { 
      let index = tipControl.selectedSegmentIndex 
     } 

     if (tipControl.selectedSegmentIndex == 3) { 

      let index = defaults.integer(forKey: "defaultTipControlKey") 
     } 


     let tipPer = tipPercentages[index] 
     let bill = Double(billField.text!) ?? 0 
     let people = Double(peopleField.text!) ?? 1 

     let tip = bill * tipPer 
     let total = bill + tip 
     let perPerson = total/people 

     tipLabel.text = String(format: "$%.2f", tip) 
     totalLabel.text = String(format: "$%.2f", total) 
     perPersonLabel.text = String(format: "$%.2f Each", perPerson) 

    } 
} 

我知道,它必須做一些事情將索引變量設置爲一個整數我試圖做,但我錯過了一些東西。任何幫助,將不勝感激。

+0

你如何使用'index'?既然所有的'index'都是在'if {'語句? 'index'是'tipPercentages [index]'中的其他內容。 –

+0

你能解決這個問題嗎? –

回答

1

的問題是,您已聲明裏面的所有if block所以它的範圍是對應於if block,因此它if block對你以後不可index不變。爲了解決這個問題,在if for塊之前聲明索引變量,而不是創建多個if塊,你只需要這樣一個單獨的if condition

var index = defaults.integer(forKey: "defaultTipControlKey") //Default value 
if (tipControl.selectedSegmentIndex != 3) { 
    index = tipControl.selectedSegmentIndex 
} 
let tipPer = tipPercentages[index] 

注:if condition並不會讓你只是想一個單一if block上面得到的索引任何意義。

+0

請檢查編輯後的答案 –

相關問題