【发布时间】:2017-01-05 06:03:51
【问题描述】:
我收到错误消息:
在下面的代码行中,“Cannot subscript a value of type of ‘[Double]’ with a index of type ‘(Any) -> 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)
}
}
我知道它必须将索引变量设置为整数,我试图这样做,但我错过了一些东西。任何帮助将不胜感激。
【问题讨论】:
-
你是如何使用
index的?由于所有index都在if {语句中定义?index是tipPercentages[index]中的其他内容。 -
您能解决问题吗?