收到错误:“无法下标类型'[Double]'的值,索引类型为'(Any) - > INT””

时间:2017-01-05 06:03:51

标签: arrays swift swift3

我收到错误:

  

“无法使用类型'(任意) - >类型的索引下标'[Double]'类型的值Int'“在以下代码行中:

tipPer = tipPercentages[index]

以下是我的其余代码(包括错误的行):((抱歉可怕的格式/语法,我是Swift的新手!)

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)

    }
}

我知道它必须做一些将索引变量设置为整数的事情,我试图这样做,但我遗漏了一些东西。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

问题是index常量,您已在所有if block内声明,因此其范围与if block相对应,因此在if block之后无法使用。要解决问题,请在for if块之前声明索引变量,而不是创建多个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上方获取索引。