A functional way to add Target in UIButton using closures

Jacky Wang
1 min readApr 20, 2016

We are all used to the good old method in UIButton to add a target.

However, sometimes it can be troublesome and annoying trying to find the function you declared, so why not do it in it more functional and Swifty way??

First we declare a closure with type alias, that takes the Sender(the button) as a parameter.

Then we extend UIButton, adding a stored property and use associatedObject in Objective-C (Swift does not support stored properties in extensions) to complete our getter and setter.

Declare a private immutable struct to store our associatedKeys,

Because associated objects only accept NSObjects instead of our associated type UIButtonTargetClosure so we need to create a ClosureWrapper that inherits NSObject to use in our TargetClosure setter getter

Now declare a function that you will call on UIButton that takes the closure as a parameter, and saves the closure to our associated_object “targetClosure”, then adds a Target to the UIButton.

Declare another function that is the default action method to referene in our addTarget method.

Now you can simply add targets to UIButton using the swify, functional way.

Now isn’t that lovely!

The full code:

--

--