如何创建运算符以实现错误链接? [英] How can I create an operator to implement error chaining?

查看:92
本文介绍了如何创建运算符以实现错误链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现以下运算符»

throwingFunction(arg: T?)».doStuff()

/*  if throwingFunction throws an error:
     print or log the error
  else 
    returns an object having the doStuff() Method 

OR 

 An Alternative design that I'm open to is 
Instead of a throwing Error, the `throwingFunction()` 
can be swapped out for a method that returns `Result` 

OR
 
a custom Type, with a generic payload type.   
*/

以下是与我正在寻找的东西类似的示例。它是使用 KeyPath 对象(归功于Sergey Smagleev
)。

Here is an example of something similar to what I'm looking for. It is a custom implementation of optional chaining made possible using the KeyPath object (credit to Sergey Smagleev ).

precedencegroup Chaining {
    associativity: left
}

infix operator ~> : Chaining

extension Optional {
  
  static func ~><T>(value: Wrapped?, key: KeyPath<Wrapped, T> ) -> T? {
    return value.map { $0[keyPath: key] }
  }
  
  static func ~><T>(value: Wrapped?, key: KeyPath<Wrapped, T?> ) -> T? {
    return value.flatMap { $0[keyPath: key] }
  }
  
}

struct Object {
    let anotherOptionalObject: AnotherObject?
}

struct AnotherObject {
    let value: String
}

let optionalObject: Object? = Object(anotherOptionalObject: AnotherObject(value: "Hello world"))

print(optionalObject~>\.anotherOptionalObject~>\.value) //this prints Optional("Hello world")
print(optionalObject?.anotherOptionalObject?.value) //this also prints Optional("Hello world")

除了,我希望实现为我提供一个通过打印或记录错误来处理错误的机会。

Except, I want the implementation to provide an opportunity for me to handle the error by printing or logging it.

推荐答案

前缀后缀一元运算符,即它们仅接受一个操作数,而中缀运算符是 binary 运算符,即它接受两个操作数。

prefix and postfix are unary operators i.e. they only accept one operand, whereas an infix operator is a binary operator i.e. it accepts two operands.

因此, 静态函数»(值:关键字:)->首选?是不正确的,因为它需要两个操作数,而您已将»定义为后缀运算符。

So, static func »(value:key:) -> Preferred? is not correct because it's taking two operands whereas you have defined » as a postfix operator.

这篇关于如何创建运算符以实现错误链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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