我想编写一个处理捕获的模板函数。可能看起来像这样
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
}
}
您可以使用接受闭包并返回元组的通用函数。
就像是:
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 {}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句