Eliasz Sawicki

Eliasz Sawicki

iOS developer from Gdansk

ReactiveCocoa 4 - CocoaActions

- 2 mins

CocoaAction is a wrapper around Action type that is available in ReactiveCocoa. (Here you can read more about Action). We use CocoaAction to bind our Actions to GUI controls. Let’s see a quick example of how it works.


Let’s imagine a situation, where we have we have a UISwitch control. Every time we switch it on or off, we want to change a MutableProperty text value.

var text = MutableProperty<String>("Switch is on")
let switchControl = UISwitch()

First, let’s create Action that will take Bool (switch’s value) as an input, return String as output and complete without errors.

let switchAction = Action<Bool, String, NoError>({ (isOn) -> SignalProducer<String, NoError> in
  return SignalProducer<String, NoError> { observer, disposable in
    observer.sendNext(isOn ? "Switch is on" : "Switch is off")

We have to wrap this action into CocoaAction that can be bound to UIControl. In order to do this, we have to remember to transform our UISwitch's value to Action's Bool input.

let switchCocoaAction = CocoaAction(switchAction, { (control) -> Bool in
    let control = control as! UISwitch
    return control.on

Now we can bind our CocoaAction to UISwitch's value change event. Remember that we have to keep reference to our switchCocoaAction.

switchControl.addTarget(switchCocoaAction, action: CocoaAction.selector, forControlEvents: .ValueChanged)

Finally, we can observe our values that are generated by executing our action and change our text value. We can do it quickly by using <~ operator that is available in ReactiveCocoa.

text <~ switchAction.values

This article is cross-posted with my my company blog

comments powered by Disqus
rss facebook twitter github youtube mail spotify lastfm instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora