0

几天前我刚刚开始学习 Swift。在我的 Xcode 游乐场中,我有以下代码:

//: Playground - noun: a place where people can play

import UIKit

enum VendingMachineError: ErrorType {
    case InvalidSelection
    case InsufficientFunds(coinsNeeded: Int)
    case OutOfStock
}


func requestBeverage(code: Int, coins: Int) throws {
    guard code > 0 else  {
        throw VendingMachineError.InvalidSelection
    }
    if coins < 2 {
        throw VendingMachineError.InsufficientFunds(coinsNeeded: 3)
    }
    guard coins > 10 else {
        throw VendingMachineError.OutOfStock
    }

    print("everything went ok")
}



try requestBeverage(-1, coins: 4)
print("finished...")

如果我尝试运行它,什么也不会发生。但我希望打印“完成......”因为在我的逻辑中,它试图做某事,失败,然后程序将继续......

所以问题是,为什么程序不继续,我如何用尽可能少的单词告诉代码在出错的情况下继续?

提前致谢

4

2 回答 2

1

do您可以使用/单独捕获所有错误catch

do {
    try requestBeverage(-1, coins: 4)
} catch VendingMachineError.InvalidSelection {
    print("Invalid selection")
} catch VendingMachineError.OutOfStock {
    print("Out of stock")
} catch VendingMachineError.InsufficientFunds(let coinsNeeded) {
    print("You need \(coinsNeeded) more coins")
} catch {
    // an unknown error occured
}

print("finished...")

或者,try?如果您只关心是否抛出错误而不关心哪个错误,请使用:

func requestSomeBeverage() {
    guard (try? requestBeverage(-1, coins: 4)) != nil else {
        print("An error has occured")
        return
    }
}

requestSomeBeverage()
print("finished...")

如果您绝对确定不会引发错误,并且希望在发生异常时引发异常,请使用try!(但在大多数情况下,不要):

try! requestBeverage(-1, coins: 4)
print("finished...")
于 2016-04-27T09:13:16.013 回答
1

你需要捕捉错误

... 

do {
  try requestBeverage(-1, coins: 4)
} catch {
  print(error)
}
print("finished...")

请参阅Swift 语言指南中的错误处理

编辑:您可以将整个表达式写在一行中;-)

do { try requestBeverage(-1, coins: 4) } catch { print(error) }
于 2016-04-26T10:59:49.920 回答