4

I'm using ReactiveCocoa in many places around my app. I've build a check to skip nil values as followed:

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)
    }
}

This helps to log failed castings, but will also fail for nil values.

In Objective-C you would simply call ignore as followed:

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

But in Swift the ignore property can't be nil. Any idea to use ignore in Swift?

Antoine
  • 23,526
  • 11
  • 88
  • 94
  • 3
    I haven't delved into the Swift API but is there a filter method? You could potentially add an 'ignoreNil' operation in an extension that just filters the original signals values on != nil ? – powerj1984 May 08 '15 at 16:35
  • ^ best solution for now I think – hhanesand May 08 '15 at 17:58

1 Answers1

2

Finally, with help from powerj1984 I created this method for now:

extension RACSignal {
    func ignoreNil() -> RACSignal {
        return self.filter({ (innerValue) -> Bool in
            return innerValue != nil
        })
    }
}
Antoine
  • 23,526
  • 11
  • 88
  • 94