千家信息网

如何理解swift错误处理

发表于:2025-01-18 作者:千家信息网编辑
千家信息网最后更新 2025年01月18日,本篇内容介绍了"如何理解swift错误处理"的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!错误处理//
千家信息网最后更新 2025年01月18日如何理解swift错误处理

本篇内容介绍了"如何理解swift错误处理"的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

错误处理

//错误处理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 = 8for 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? 如果抛出错误,程序不会崩溃,会返回nilfunc 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() {            //        }        //    }}

"如何理解swift错误处理"的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注网站,小编将为大家输出更多高质量的实用文章!

0