---
layout: post
title: ReactiveCocoa 4 - CocoaActions
tags: iOS
comments: true
author: eliasz
---

`CocoaAction` is a wrapper around `Action` type that is available in ReactiveCocoa. ([Here ](http://eluss.github.io/reactivecocoa-4-action/) 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.

Example
===
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.

{% highlight swift %}

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

{% endhighlight %}

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

{% highlight swift %}
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")
    observer.sendCompleted()
  }
})
{% endhighlight %}

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.

{% highlight swift %}
let switchCocoaAction = CocoaAction(switchAction, { (control) -> Bool in
    let control = control as! UISwitch
    return control.on
})
{% endhighlight %}
Now we can bind our `CocoaAction` to `UISwitch's` value change event. Remember that we have to keep reference to our switchCocoaAction.
{% highlight swift %}
switchControl.addTarget(switchCocoaAction, action: CocoaAction.selector, forControlEvents: .ValueChanged)
{% endhighlight %}

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`.
{% highlight swift %}
text <~ switchAction.values
{% endhighlight %}

*This article is cross-posted with my [my personal blog](http://eluss.github.io/).*

Add ReactiveCocoa 4 CocoaAction post
Add ReactiveCocoa 4 CocoaAction post
