Search code examples
iosreactive-cocoareactive-cocoa-3

mapAs, filterAs, subscribeNextAs for ReactiveCocoa 3.0


Saw on Colin Eberhart's pdfs floating around that he made those extensions himself. He had written subscribeNextAs but not any of the others in Swift.

Is the below correct?

extension RACSignal {

    func subscribeNextAs<T>(nextClosure:(T) -> ()) -> () {
        self.subscribeNext {
        (next: AnyObject!) -> () in
            let nextAsT = next as! T
            nextClosure(nextAsT)
        }
    }

    func filterAs<T>(nextClosure:(T!) -> Bool) -> (RACSignal) {
            return self.filter {
                (next: AnyObject!) -> Bool in
                if(next == nil){
                    return nextClosure(nil)
                }else{
                    let nextAsT = next as! T
                    return nextClosure(nextAsT)
                }
            }
    }

    func mapAs<T>(nextClosure:(T!) -> AnyObject!) -> (RACSignal) {
            return self.map {
                (next: AnyObject!) -> AnyObject! in
                if(next == nil){
                    return nextClosure(nil)
                }else{
                    let nextAsT = next as! T
                    return nextClosure(nextAsT)
                }
            }
    }


}

Solution

  • Even though what you wrote seems to be correct, those Colin Eberhart's extensions were made a lot time ago for the RAC v2, when RAC v3 was in early development stage. Nowadays it's a Release Candidate version already, so why not use it instead? It's handy enough. Xcode will automatically detect Signal's type

    intSignal
        |> filter { num in num % 2 == 0 }
        |> map(toString)
        |> observe(next: { string in println(string) })
    

    More info in README.md or Documentation folder