Swift readLine!造成致命错误“执行中断”

时间:2016-03-28 06:56:52

标签: 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":
                //
            case "2":
                //
            case "3":
                //
            default:
                choice = "Invalid"
                try sell()
        }
}

try sell()

它给了我错误

  

执行被中断的原因是exc_bad_instruction

我意识到了!导致错误。如果我将其删除,则switch内的比较存在问题。

任何人都知道这是什么问题?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

如果要检查它是否包含值还是nil

,请创建一个
    let product = readLine(stripNewline: true)
    if let productNo = product {
        switch productNo {
          //your same code in switch
}