本篇內容介紹了“如何理解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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。