Idea: Extend "guard" to try-statements, with a catch block


(Anton Zhilin) #1

By the way, you can write a helper for immediate handling of errors:

public func handle<T>(@autoclosure body: () throws -> T, errorHandler:
(ErrorType) -> ()) -> T? {
    do {
        return try body()
    } catch e {
        errorHandler(e)
        return nil
    }
}

func dangerousMethod() throws -> Int { /*...*/ }

let result: Int? = handle(try dangerousMethod()) { /*...*/ }
result ?? 0

guard let result = handle(try dangerousMethod(), log) {
    return
}