在RXSwift中获取与.success Result关联的值的正确语法是什么?
.map{ (result : Result<Double>) -> Double in
//how to get duration from result? this does not work
let duration : Double = result.success.value
return duration
}
添加泛型扩展:
enum Result<T> {
case success(T)
case failure(Error)
}
extension Result {
var successResult: T? {
guard case let .success(value) = self else { return nil }
return value
}
}
有了上述方法,您可以做到:
result.successResult.map { duration in
// do something with duration
}
Swift 中的 Result 有一个 get(( 函数,该函数以抛掷表达式的形式返回成功值。所以你可以这样称呼:
var successVal = try? result.get()