ReactiveCocoa在Swift中忽略nil

时间:2015-05-08 11:46:20

标签: swift reactive-cocoa

我在我的应用程序周围的许多地方使用ReactiveCocoa。我已构建一个检查以跳过nil值,如下所示:

func subscribeNextAs<T>(nextClosure:(T) -> ()) -> RACDisposable {
    return self.subscribeNext {
        (next: AnyObject!) -> () in
        self.errorLogCastNext(next, withClosure: nextClosure)
    }
}

private func errorLogCastNext<T>(next:AnyObject!, withClosure nextClosure:(T) -> ()){
    if let nextAsT = next as? T {
        nextClosure(nextAsT)
    } else {
        DDLogError("ERROR: Could not cast! \(next)", level: logLevel, asynchronous: false)
    }
}

这有助于记录失败的铸件,但也会因nil值而失败。

在Objective-C中,您只需按以下方式调用ignore:

[[RACObserve(self, maybeNilProperty) ignore:nil] subscribeNext:^(id x) {
  // x can't be nil
}];

但在Swift中,ignore属性不能是nil。有没有想过在Swift中使用ignore?

1 个答案:

答案 0 :(得分:2)

最后,在powerj1984的帮助下,我现在创建了这个方法:

extension RACSignal {
    func ignoreNil() -> RACSignal {
        return self.filter({ (innerValue) -> Bool in
            return innerValue != nil
        })
    }
}
相关问题