ReactiveCocoa 在 Swift 中忽略 nil
ReactiveCocoa ignore nil in Swift
我在应用的很多地方都使用了 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 中忽略 属性 不能是 nil
。知道在 Swift 中使用忽略吗?
最后,在 powerj1984 的帮助下,我暂时创建了这个方法:
extension RACSignal {
func ignoreNil() -> RACSignal {
return self.filter({ (innerValue) -> Bool in
return innerValue != nil
})
}
}
我在应用的很多地方都使用了 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 中忽略 属性 不能是 nil
。知道在 Swift 中使用忽略吗?
最后,在 powerj1984 的帮助下,我暂时创建了这个方法:
extension RACSignal {
func ignoreNil() -> RACSignal {
return self.filter({ (innerValue) -> Bool in
return innerValue != nil
})
}
}