当我在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")
}
}
}
答案 0 :(得分:0)
您必须从textField获取Text,这是一个String类型,而不是数字。您必须先将其转换为数字,然后在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")
}