swift基础之错误处理

原创
2021/04/20 09:46
阅读数 41

错误处理

//错误处理
enum VendingMachineError: Error {
    case invalidSelection
    case insufficientFunds(coinsNeeded: Int)
    case outOfStock
}

struct Item {
    var price: Int
    var count: Int
}

class VendingMachine {
    var inventery = [
        "Candy Bar": Item(price: 12, count: 7),
        "Chips": Item(price: 10, count: 4),
        "Pretzels": Item(price: 7, count: 11)
    ]
    
    var coinsDeposited = 0
    
    func vend(itemNeed name: String) throws {
        guard let item = inventery[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
        inventery[name] = newItem
        
        print("show \(name)")
    }
}

let favoriteSnacks = [
    "Alice": "Chips",
    "Bob": "Licorice",
    "Eve": "Pretzels"
]

func buyFavoriteSnack(person: String, vendingMachine: VendingMachine) throws {
    let snackName = favoriteSnacks[person] ?? ""
    try vendingMachine.vend(itemNeed: snackName)
}

//使用Do-Catch做错误处理
var vendingMachine = VendingMachine()
vendingMachine.coinsDeposited = 8
for p in favoriteSnacks {
    do {
        try buyFavoriteSnack(person: p.key, vendingMachine: vendingMachine)
        print("\(p.key) success!")
    } catch VendingMachineError.invalidSelection {
        print("\(p.key) Invalid Selection")
    } catch VendingMachineError.outOfStock {
        print("\(p.key) Out of stock")
    } catch VendingMachineError.insufficientFunds(let coinsNeeded) {
        print("\(p.key) need insert an additional \(coinsNeeded) coins.")
    } catch {
        print("Unexpected error:\(error).")
    }
}

try? 如果抛出错误,程序不会崩溃,会返回nil

//try? 如果抛出错误,程序不会崩溃,会返回nil
func someThrowingFunction() throws -> Int {
    //
    return 1
}

let x = try? someThrowingFunction()

//等价
let y: Int?
do {
    y = try someThrowingFunction()
} catch {
    y = nil
}

try! 中断错误传播

如果错误真的发生,会得到运行时错误

//try! 中断错误传播,如果错误真的发生,会得到运行时错误
let photo = try! someThrowingFunction()

defer 退出前的清理动作

//指定退出前的清理动作 defer 关键字
func processFile(filename: String) throws {
    if exists(filename) {
        let file = open(filename)
        defer {
            close(file)
        }
        while let line = try file.readline() {
            //
        }
        //
    }
}
展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部