錯誤處理

The Swift Programming Language (Swift 2.1) - Error Handling

在 Objective-C 時,我們經常定義這樣的函式來取得執行後產生的 error

- (void)doSomethingWithInput:(NSString)input error:(NSError**)error {
    // 建立 NSError
    NSError *not_found_error = [NSError errorWithDomain:@"myDomain" 
                                                   code:404 
                                               userInfo:@{NSLocalizedDescriptionKey:@"not found"}];
    // 然後把指標指向error
    *error = not_found_error;
}

在 Swift 我們是這樣定義的

func doSomething(input:String) throws ->Void {
    // throw error


}

使用上也有些許的不同, 要使用 do/try/catch 來執行有throws 的函式

do {
    try doSomething("demoString")
    // ...
    try doSomething2("demoString")
    // ...
    try doSomething3("demoString")
    // ...
} catch let error as NSError {
    print(error.localizedDescription)
}

或是無視 error, 但是…這樣好嗎?哈

let value = try! doSomething("demoString")
let op_value = try? doSomething("demoString")

最好的方式是再定義 ErrorType 會再好



results matching ""

    No results matching ""