gpt4 book ai didi

swift - 错误: Expression pattern of type 'CountableClosedRange' cannot match values of type 'UITextField!'

转载 作者:行者123 更新时间:2023-11-30 11:42:42 24 4
gpt4 key购买 nike

当我在 Swift 中构建并运行此代码时,出现上述错误。我正在尝试这样做,以便用户可以输入一个数字,并且 switch 语句将返回与该数字对应的以下打印内容。

import UIKit

class ViewController: UIViewController {
@IBOutlet weak var numberInput: UITextField!

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

@IBAction func inputText(_ sender: Any) {

switch numberInput {

case 0 ... 50:
print("Number is between 0 & 50")
case 51 ... 100:
print("Number is between 51 & 100")
case 101 ... 150:
print("Number is between 101 & 150")
default:
print("Fallback option")
}
}
}

最佳答案

您必须从文本字段中获取文本,它是字符串类型,而不是数字。您必须先将其转换为数字,然后在采用整数范围的 switch 语句中使用它。

guard let text = numberInput?.text,let number = Int(text) else { return }
switch number {

case 0 ... 50:
print("Number is between 0 & 50")
case 51 ... 100:
print("Number is between 51 & 100")
case 101 ... 150:
print("Number is between 101 & 150")
default:
print("Fallback option")
}

关于swift - 错误: Expression pattern of type 'CountableClosedRange<Int>' cannot match values of type 'UITextField!' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49165849/

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