我收到錯誤:
收到錯誤:「不能與類型的索引,下標類型的‘[雙]’值‘(任何) - >內部’」
「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)
}
}
我知道,它必須做一些事情將索引變量設置爲一個整數我試圖做,但我錯過了一些東西。任何幫助,將不勝感激。
你如何使用'index'?既然所有的'index'都是在'if {'語句? 'index'是'tipPercentages [index]'中的其他內容。 –
你能解決這個問題嗎? –