忽略/过滤零

时间:2016-04-11 19:36:12

标签: swift rx-swift reactivex

是否有可以过滤nil的运算符?我最接近的是这里提到的解决方案:https://github.com/ReactiveX/RxSwift/issues/209#issuecomment-150842686

相关摘录:

public protocol OptionalType {
    func hasValue() -> Bool
}

extension Optional: OptionalType {
    public func hasValue() -> Bool {
        return (self != nil)
    }
}

public extension ObservableType where E: OptionalType {
    @warn_unused_result(message="http://git.io/rxs.uo")
    public func notNil() -> Observable<E> {
        return self.filter { $0.hasValue() }
    }
}

但是,在.notNil()之后,E仍然是可选的,因此后续的链式运算符仍会将self视为Observer<E>,其中E是可选的。所以我仍然需要一个额外的运算符:

.map { (username: String?) -> String in
    return username!
}

我一定错过了什么。这似乎是一个非常普遍的需求。

3 个答案:

答案 0 :(得分:1)

https://github.com/RxSwiftCommunity/RxSwift-Ext点检unwrap:)

https://github.com/RxSwiftCommunity/RxOptional

目前,您应该根据个人需要使用RxOptional 但是,RxSwift-Ext将在未来2-3个月内呈指数级增长:)

P / S:这些家伙(我正在谈论这些回购的所有者)每天都在RxSwift的闲谈中与对方聊天:))

答案 1 :(得分:0)

在RxSwift 5中,可以使用核心库中的compactMap

observable.compactMap { $0 }

答案 2 :(得分:0)

  • 要过滤掉 nil 值,请使用 RxSwiftExt.unwrap()
  • 要仅过滤 nil 值,只需执行以下操作:
observableContainingNils.filter { $0 == .none }