美文网首页swift学习笔记
第十八章 错误处理

第十八章 错误处理

作者: 运柱 | 来源:发表于2017-07-20 14:28 被阅读0次

    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)

    相关文章

      网友评论

        本文标题:第十八章 错误处理

        本文链接:https://www.haomeiwen.com/subject/unndkxtx.html