gpt4 book ai didi

arrays - 收到错误 : “Cannot subscript a value of type ‘[Double]’ with an index of type ‘(Any) -> Int’ ”

转载 作者:行者123 更新时间:2023-11-28 15:57:45 25 4
gpt4 key购买 nike

我收到错误:

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

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)

}
}

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

最佳答案

问题是您在所有 if block 中声明的 index 常量,因此它的范围对应于该 if block 所以它在 if block 之后对您不可用。要解决这个问题,请在 for if block 之前声明索引变量,而不是创建多个 if block ,您只需要像这样的单个 if condition

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

注意:您的if 条件 没有任何意义,您只想在一个if block 之上获取索引。

关于arrays - 收到错误 : “Cannot subscript a value of type ‘[Double]’ with an index of type ‘(Any) -> Int’ ”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41478248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com