首页 > 解决方案 > 如何快速实现自定义错误抛出语法?

问题描述

我想实现以下内容:

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. 
*/

我不确定在源代码中的何处查找有关如何do, try, catch实现的示例。Swift 错误文档解释了如何使用已经实现的错误处理方法。需要明确的是,我想使用上述语法实现自定义错误处理。

就像是:

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
        }
    }
}

标签: swifterror-handlingsyntaxsyntax-error

解决方案



推荐阅读