如何编写处理的模板函数

时间:2018-10-25 09:06:43

标签: swift

我想编写一个处理捕获的模板函数。可能看起来像这样

func handleMethod(methodNeedToHandle) -> result: notSureType{
    var result
    do {
        let response = try handleMethod
        result = response
        return result
    } catch let error as someObjectError{
        result = error
        return result
    }  
}

然后您可以像使用它

let catchResult = handleMethod(method(x: something, y: something))

谢谢大家的帮助,我在下面提供了工作代码

func handleDoTryCatch<T>(closure:() throws -> T) -> Any {
    do {
        let result = try closure()
        return result
    } catch let error {
        return error
    }
}

3 个答案:

答案 0 :(得分:1)

您可以使用接受闭包并返回元组的通用函数。

类似的东西:

func handle<T>(closure:() throws -> T) -> (T?, Error?) {
    do {
        let result = try closure()
        return (result, nil)
    } catch let error {
        return (nil, error)
    }
}

这将定义一个函数,该函数带有一个闭包,该闭包调用可以抛出的方法。它返回一个具有预期返回类型和符合Error协议的元组。

您将像这样使用它:

let result: (Void?, Error?) = handle { try someFunc() }
let result2: (Int?, Error?) = handle { try someOtherFunc(2) }

someFunc和someOtherFunc只是示例,它们的签名为:

func someFunc() throws {}
func someOtherFunc(_ param: Int) throws -> Int {}

答案 1 :(得分:0)

我最接近您可能想要的是: (快速游乐场代码:)

func handleMethod(_ f: @autoclosure () throws -> Void) -> Error? {
    do {
        try f()
    } catch let err {
        return err
    }
    return nil
}

enum HelloError: Error {
    case tooShort
}

func hello(_ what: String) throws {
    guard what.count > 0 else { throw HelloError.tooShort }
    print ("Hello \(what)!")
}

// use like this:
// let err = handleMethod(try hello("World")) // err == nil
// let err = handleMethod(try hello(""))      // err == HelloError.tooShort
// 

print ("* hello(\"World\") -> \(String(describing: handleMethod(try hello("World"))))")
print ("* hello(\"\") -> \(String(describing: handleMethod(try hello(""))))")

这将产生以下输出:

Hello World!
* hello("World") -> nil
* hello("") -> Optional(__lldb_expr_3.HelloError.tooShort)

考虑按照George_E的建议仅使用do / catch即可。这是一个很好的建议。但是,如果您需要此功能,那么希望它能为您提供一个起点。

答案 2 :(得分:0)

这是我设法提供的功能:

// Your error cases
enum Errors: Error {
    case someErrorCase
}


// Function to test another function
func doTryCatch<T>(for function: () throws -> T) {
    do {
        let returnValue = try function()
        print("Success! The return value is \(returnValue)")
    } catch {
        print("Error! The error reason was \"\(String(describing: error))\"")
    }
}


// Function to test
func failingFunction() throws -> Int {
    throw Errors.someErrorCase // <-- Comment this to not recieve an error (for testing)
    return 5 // Will return 5 if the error is not thrown

    // Failure: Error! The error reason was "someErrorCase"
    // Success: Success! The return value is 5
}


// Perform the test
doTryCatch(for: failingFunction) // <-- Very easy to test, no closures to write!

希望这有助于调试! :)