Swift 快速阅读!“正在导致致命错误”;“执行被中断”;

Swift 快速阅读!“正在导致致命错误”;“执行被中断”;,swift,readline,Swift,Readline,我有这段代码 func sell() throws{ while(true) { var choice : String? print("Please press a number from 1 to 3\n") let product = readLine(stripNewline: true)! switch product { case "1":

我有这段代码

func sell() throws{
    while(true)
    {
        var choice : String?
        print("Please press a number from 1 to 3\n")
        let product = readLine(stripNewline: true)!
        switch product
        {
            case "1":
                //
            case "2":
                //
            case "3":
                //
            default:
                choice = "Invalid"
                try sell()
        }
}

try sell()
这给了我一个错误

执行被中断,原因是exc\u错误\u指令

我意识到了!正在导致错误。如果我将其删除,则
开关内的比较将出现问题


有人知道问题出在哪里吗?

如果让我们检查这个值是包含值还是为零,那么创建一个怎么样

    let product = readLine(stripNewline: true)
    if let productNo = product {
        switch productNo {
          //your same code in switch
}
func foo()->Int {
    print("Please press a number from 1 to 3")
    while true {
        if let l = readLine(),
            let i = Int(l) {
            if (1..<4).contains(i) {
                return i
            } else {
                print("Number must be in range from 1 to 3")
            }
        } else {
            print("Please press a number")
        }
    }
}
let r = foo()
print("You chose", r)
Please press a number from 1 to 3
u
Please press a number
7
Number must be in range from 1 to 3
45
Number must be in range from 1 to 3
h76
Please press a number
1
You chose 1
Program ended with exit code: 0