iosswiftreactive-cocoareactive-cocoa-3

How to Convert NSError SignalProducer to NoError SignalProducer in ReactiveCocoa (Swift)


I have a model with a MutableProperty<Bool> and I have a UIButton (ctaTopButton) that should flip that property when it's pressed, for example, on click true becomes false and vice versa.

I have it setup this way:

let producer = ctaTopButton.rac_signalForControlEvents(UIControlEvents.TouchUpInside).toSignalProducer()
    |> map {value in !self.model.enabled.value}


// model.enabled <~ producer  

The crux of my issues comes from rac_signalForControlEvents(...).toSignalProducer() returns a SignalProducer<AnyObject?, NSError> which the map converts to SignalProducer<Bool, NSError>

The infix operator <~ however only works with SignalProducer<Bool, NoError> so I need to convert my producer somehow.

My question is, how do I demote errors? I know there is a promoteErrors for converting NoError to NSError. There is also mapError though I can't figure out how get back an instance of NoError as it has no initializers.


Solution

  • You can use catch() operator for that case like:

    let producer = ctaTopButton.rac_signalForControlEvents(.TouchUpInside).toSignalProducer()
        |> map { value in !self.model.enabled.value }
        |> catch { _ in SignalProducer<Bool, NoError>.empty }