Swift 5.x 错误处理

2020-07-13  本文已影响0人  ShenYj
1. 错误表示
enum VendingMachineError: Error {
    case invalidSelection
    case insufficientFunds(coinsNeeded: Int)
    case outOfStock
}

2. 如何抛出错误
func canThrowErrors() throws -> String
func cannotThrowErrors() -> String

e.g.

enum VendingMachineError: Error {
    case invalidSelection
    case insufficientFunds(coinsNeeded: Int)
    case outOfStock
}

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

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


let favoriteSnacks = [
    "Alice": "Chips",
    "Bob": "Libcorice",
    "Eve": "Pretzels"
]
func buyFavoriteSnack(person: String, vendingMachine: VendingMachine) throws {
    let snackName = favoriteSnacks[person] ?? "Candy Bar"
    try vendingMachine.vend(itemNamed: snackName)
}


3. 使用Do-Catch做错误处理
do {
    try <#throwing expression#>
    <#statements#>
} catch <#pattern#> {
    <#statements#>
} catch <#pattern#> where <#condition#> {
    <#statements#>
} catch {
    <#statements#>
}

e.g.

var vendingMachine = VendingMachine()
vendingMachine.coinsDeposited = 8
do {
    try buyFavoriteSnack(person: "Alice", vendingMachine: vendingMachine)
    print("Success! Yum.")
} catch VendingMachineError.invalidSelection {
    print("Invalid selection")
} catch VendingMachineError.outOfStock {
    print("Out of Stock")
} catch VendingMachineError.insufficientFunds(let coinsNeeded) {
    print("insufficientFunds funds. Please insert an additional \(coinsNeeded) coins")
} catch {
    print("Unexpected error: \(error).")
}

4. try?

e.g.

func someThrowingFunction() throws -> Int {
    //...
    return 1
}

let x = try? someThrowingFunction()

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

5. try!

e.g.

let phone = try! loadImage(atPath: "./Resources/John Appleseed.jpg")

6. defer 指定退出的清理动作
func processFile(fileName: String) throws {
    if exists(fileName) {
        let file = open(fileName)
        defer {
            close(file)
        }
    }
    while let line = try file.readline() {
        // Work with the file.
    }
    // close(file) is called here, at the end of scope.
}
上一篇下一篇

猜你喜欢

热点阅读