错误:“CountableClosedRange <int>”类型的表达式模式不能匹配“UITextField!”类型的值

时间:2018-03-08 05:11:54

标签: swift switch-statement uitextfield case

当我在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")
        }
    }
}

1 个答案:

答案 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")
    }