Swift 2 学习笔记 20.错误处理

课程来自慕课网liuyubobobo老师


错误处理
  • 强制退出程序
var pocketMoney:Int = 20
// assert: In -O builds (the default for Xcode’s Release configuration), condition is not evaluated, and there are no effects.
assert(pocketMoney > 10)
assert(pocketMoney > 20 , "No enough money")
// In -O builds, has no effect.
assertionFailure("Error")
// precondition: In -O builds (the default for Xcode’s Release configuration): If condition evaluates to false, stop program execution.
precondition(pocketMoney > 10)
precondition(pocketMoney > 20, "No enough money")
// fatalError:无条件地打印给定的消息并停止执行
fatalError("Error")
  • 错误处理
class VendingMachine {
    
    struct Item {
        enum Drink: String {
            case Water
            case Cola
            case Juice
        }
        
        let drink: Drink
        let price: Int
        var count: Int
    }
    
    enum SomeError: Error {
        case NoSuchItem
        case NotEnoughMoney(Int)
        case OutOfStock
    }
    
    private var items = ["Water": Item(drink: .Water, price: 2, count: 10), "Coca Cola": Item(drink: .Cola, price: 3, count: 5), "Orange Juice": Item(drink: .Juice, price: 5, count: 3)]
    
    func display() {
        print("Welcome")
        for itemName in items.keys {
            print("*",itemName)
        }
        print("=====================")
    }
    
    private func dispenseItem(_ itemName: String) {
        items[itemName]!.count -= 1
        print("Enjoy your",itemName)
    }
    
    func vend(itemName: String,money: Int) throws-> Int {
        //延迟到函数末执行,无论是否抛出异常
        defer {
            print("Have a nice day!")
        }
        
        guard let item = items[itemName] else {
            throw SomeError.NoSuchItem
        }
        
        guard money >= item.price else {
            throw SomeError.NotEnoughMoney(item.price)
        }
        
        guard item.count > 0 else {
            throw SomeError.OutOfStock
        }
        
        dispenseItem(itemName)
        
        return money - item.price
    }
}

let machine = VendingMachine()
machine.display()

var pocketMoney = 4

do {
    pocketMoney = try machine.vend(itemName: "Coca Cola", money: pocketMoney)
    print(pocketMoney,"Yuan left")
}
catch VendingMachine.SomeError.NoSuchItem {
    print("No Such Item")
}
catch VendingMachine.SomeError.NotEnoughMoney(let price) {
    print("Not Enough Money.",price,"Yuan need")
}
catch VendingMachine.SomeError.OutOfStock {
    print("Out Of Stock")
}
catch {
    print("Other Error")
}

do {
    pocketMoney = try machine.vend(itemName: "Coca Cola", money: pocketMoney)
    print(pocketMoney,"Yuan left")
}
catch let error as VendingMachine.SomeError {
    print(error)
}
catch {
    print("Other Error")
}

你可能感兴趣的:(Swift 2 学习笔记 20.错误处理)