swift - 如何创建运算符来实现错误链接?
问题描述
我想实现以下运算符»
:
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")
除了,我希望实现为我提供一个通过打印或记录错误来处理错误的机会。
解决方案
prefix
并且postfix
是一元运算符,即它们只接受一个操作数,而infix
运算符是二元运算符,即它接受两个操作数。
因此,static func »(value:key:) -> Preferred?
这是不正确的,因为它采用两个操作数,而您已将其定义»
为postfix
运算符。
推荐阅读
- actions-on-google - 操作审批流程是否需要请求同步功能
- swift - Firebase 与 SwiftUI 的集成
- fortran - 具有滑动访问的 MPI 共享内存通信
- powerquery - 如何逐步通过 M 中的评估函数
- powershell - powershell 调试:脚本与本地、全局和自动
- android - AAPT2 aapt2-3.4.0 linux 守护进程:守护进程启动失败
- python - 在 Gurobi 目标函数中添加许多二次项
- logging - 我可以在测试期间创建一个有生命周期的记录器吗?
- javascript - 如何从复选框标签中的锚点显示模式
- delphi - Delphi Rio 10.3.2:从 ZIP 文件中删除文件