swift Swift中的错误处理示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift Swift中的错误处理示例相关的知识,希望对你有一定的参考价值。

struct Car {
    private let MAX_PRICE: Double = 50000
    var price: Double
    var type: CarType
    
    //Error-handling by value
    mutating func discountPrice(amount: Double) -> Bool {
        guard price - amount > 0 else {
            return false
        }
        price -= amount
        return true
    }
    
    //Error handling with ErrorType & 'throws'
    mutating func increasePrice(amount: Double) throws -> Double {
        //defer block is for code to be executed last, regardless if errors occured
        defer {
            print("Price Change Fee added")
            price += 2.50
        }
        
        print("Attempting to increase price price by: \(amount)")
        
        guard price + amount < MAX_PRICE else {
            throw ExError.PriceError(amountOutOfRange: (price + amount) - MAX_PRICE)
        }
        
        price += amount
        return price
    }
 }

enum CarType {
    case Coupe, Convertible
}

//Swift uses ErrorType instead of NSError
enum ExError: ErrorType {
    case BasicError
    case PriceError(amountOutOfRange: Double)
}

// Example Error Handling by return value
var car = Car(price: 1000.45, type: .Coupe)
assert(car.discountPrice(500))
print(car.price)
assert(!car.discountPrice(1000))
print(car.price)

//Error Handling by Error Type
do {
    try car.increasePrice(100000)
} catch ExError.PriceError(let amountOutOfRange) {
    print("Car overpriced by: \(amountOutOfRange)")
}

//Optionally attempt to perform operation do nothing with caught exception
try? car.increasePrice(100000) //returns nil

//Optionally handle return value, do not handle exception
if let price = try? car.increasePrice(100) {
    print("\(price)")
}

以上是关于swift Swift中的错误处理示例的主要内容,如果未能解决你的问题,请参考以下文章

swift swift中的错误处理3

Swift 2 中的显式老式错误处理

《从零开始学Swift》学习笔记(Day 52)——Cocoa错误处理模式

Swift中的错误处理

Swift 中的完成处理程序错误

Swift 中的正确错误处理