如何快速实现自定义错误抛出语法? [英] How can I implement a custom error throwing syntax in swift?

查看:54
本文介绍了如何快速实现自定义错误抛出语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要实现以下内容:

throwingFunction()??.doStuff()
/*  if throwingFunction throws an error:
     print the error
  else 
    returns an object with the doStuff() Method 
*/


throwingFunction()??
/*
 if an error is thrown, 
    prints the error.  
 else 
    execute the function without errors. 
*/

我不确定在源代码举例说明了如何如何做,尝试,捕捉已实施。 快速错误文档说明了如何使用已经存在的错误处理方法已实施。需要明确的是,我想使用上述语法实现自定义错误处理。

I'm not sure where to look in the source code for examples on how do, try, catch were implemented. The Swift error docs explain how to use error handle methods that are already implemented. To be clear, I want to implement custom error handling with the above syntax.

类似的东西:

precedencegroup Chaining {
    associativity: left
}

infix operator ?? : Chaining

extension Result {
    
  // ERROR: Unary operator implementation must have a 'prefix' or 'postfix' modifier
    static func ??(value: Result<Success, Failure>) -> Success? { 
        switch value {
        case .success(let win):
            return win
        case .failure(let fail):
            print(fail.localizedDescription)
            return nil
        }
    }
}


推荐答案

您可以定义一个后缀运算符,该运算符将一个引发闭包作为(左)操作数。 ?? 已被定义为中缀运算符,因此您必须选择其他名称:

You can define a postfix operator which takes a throwing closure as (left) operand. ?? is already defined as an infix operator, therefore you have to choose a different name:

postfix operator <?>

postfix func <?><T>(expression: () throws -> T) -> T? {
    do {
        return try expression()
    } catch {
        print(error)
        return nil
    }
}

现在您可以打电话

let result = throwingFunc<?>

或与

let result = (throwingFunc<?>)?.doStuff()




先前的答案:

?? 已被定义为中缀运算符。对于后缀运算符,您必须选择其他名称,例如:

?? is already defined as an infix operator. For a postfix operator you have to choose a different name, for example:

postfix operator <?>

extension Result {
    static postfix func <?>(value: Result) -> Success? {
        switch value {
        case .success(let win):
            return win
        case .failure(let fail):
            print(fail.localizedDescription)
            return nil
        }
    }
}

现在您可以打电话

let res = Result(catching: throwingFunc)<?>

或与

let res = (Result(catching: throwingFunc)<?>)?.doStuff()

这篇关于如何快速实现自定义错误抛出语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆