首页 > 解决方案 > 如何创建运算符来实现错误链接?

问题描述

我想实现以下运算符»

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 )实现的可选链接的自定义实现。

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")

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

标签: swifterror-handling

解决方案


prefix并且postfix一元运算符,即它们只接受一个操作数,而infix运算符是二元运算符,即它接受两个操作数。

因此,static func »(value:key:) -> Preferred?这是不正确的,因为它采用两个操作数,而您已将其定义»postfix运算符。


推荐阅读