本篇内容介绍了“如何理解swift错误处理”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
创新互联公司是一家专注于成都做网站、网站制作、成都外贸网站建设与策划设计,岳普湖网站建设哪家好?创新互联公司做网站,专注于网站建设10多年,网设计领域的专业建站公司;建站业务涵盖:岳普湖等地区。岳普湖做网站价格咨询:028-86922220
//错误处理 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错误处理”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注创新互联网站,小编将为大家输出更多高质量的实用文章!