第十八章 错误处理

enum VendingMachineError: Error {

    case invalidSelection

    case insufficientFunds(coinsNeeded: Int)

    case outOfStock

}

do {

    throw VendingMachineError.insufficientFunds(coinsNeeded: 5)

} catch VendingMachineError.insufficientFunds(let coinsNeeded) {

    print("Insufficient funds. Please insert \(coinsNeeded)")

}

struct Item {

    var price: Int

    var count: Int

}

class VendingMachine {

    var inventory = [

        "Candy Bar": Item(price: 12, count: 7),

        "Chips": Item(price: 10, count: 4),

        "Pretzels": Item(price: 7, count: 11)

    ]

    var coinsDeposited = 0

    func dispenseSnack(snack: String) {

        print("Dispensing \(snack)")

    }

    func vend(itemNamed name: String) throws {

        guard let item = inventory[name] else {

            throw VendingMachineError.invalidSelection

        }

        guard item.count > 0 else {

            throw VendingMachineError.outOfStock

        }

        guard item.price <= coinsDeposited else {

            throw VendingMachineError.insufficientFunds(coinsNeeded: item.price -    coinsDeposited)

        }

        coinsDeposited -= item.price

        var newItem = item

        newItem.count -= 1

        inventory[name] = newItem

        print("Dispensing \(name)")

    }

}

let favoriteSnacks = [

    "Alice": "Chips",

    "Bob": "Licorice",

    "Eve": "Pretzels",

]

func buyFavoriteSnack(person: String, vendingMachine: VendingMachine) throws {

    let snackName = favoriteSnacks[person] ?? "Candy Bar"

    try vendingMachine.vend(itemNamed: snackName)

}

let vendintMachine = VendingMachine()

vendintMachine.coinsDeposited = 20

do {

    try buyFavoriteSnack(person: "Alice", vendingMachine: vendintMachine)

} catch VendingMachineError.invalidSelection {

    print("invalid selection")

} catch VendingMachineError.insufficientFunds(let coinsNeeded) {

    print("insufficient funds")

} catch VendingMachineError.outOfStock {

    print("out of stock")

}

print(vendintMachine.coinsDeposited)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 126.析构器 在一个类实例销毁前,一个析构器会立即调用。使用deinit 关键字来表示析构器, 跟构造器写法类似...
    无沣阅读 4,292评论 0 4
  • try catch 的使用示例 空合运算符(Nil Coalescing Operator) ps.以上代码类似 ...
    无名氏_1阅读 5,275评论 0 0
  • 1.表示并抛出错误 在 Swift 中,错误用符合Error协议的类型的值来表示。这个空协议表明该类型可以用于错误...
    思考的快与慢阅读 3,931评论 0 0
  • 昨天惊蛰,时间过的真快,转瞬间春节已经过去一个多月了。每年的这段时间都会为一些朋友预测年运,说实话,这个事情...
    去痛片_af8b阅读 3,207评论 0 1
  • 自闺女出生,开始喜欢观察宝宝。小宝宝的本事可大了,她没有我们想象的柔弱。 刚出生她...
    妮妮abc阅读 1,873评论 0 2

友情链接更多精彩内容