本篇内容介绍了“如何理解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 = 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 func someThrowingFunction() throws -> Int { // return 1 } let x = try? someThrowingFunction() //等价 let y: Int? do { y = try someThrowingFunction() } catch { y = nil }
如果错误真的发生,会得到运行时错误
//try! 中断错误传播,如果错误真的发生,会得到运行时错误 let photo = try! someThrowingFunction()
//指定退出前的清理动作 defer 关键字 func processFile(filename: String) throws { if exists(filename) { let file = open(filename) defer { close(file) } while let line = try file.readline() { // } // } }
“如何理解swift错误处理”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。