Event Dispatching in Swift with Protocol Extensions


via Event Dispatching in Swift with Protocol Extensions.

One of the highlights for Swift 2.0 at WWDC was the introduction of protocol extensions: the ability to add default method implementations to protocols. Plenty has been written about protocol oriented programming in Swift since WWDC from bloggers such as SketchyTech, David Owens and Ray Wenderlich, and I thought it was high time to put my own spin on it.

After working with event dispatching in ActionScript for may years, protocol extensions seemed the perfect technique to implement a similar pattern in Swift. Indeed, protocol extensions offer the immediate advantage that I can add event dispatching to any type of object without the need for that object to extend a base class. For example, not only can user interface components dispatch events, but value objects and data structures can too: perfect for the MVVM pattern where a view may react to events on the view model to update itself.

My project, Protocol Extension Event Dispatcher, contains a demonstration application containing a handful of user interface components: a slider, a stepper, a label and a button. There’s a single ‘model’: an integer that dispatches a change event when its value changes via those components.  The end result is when the user interacts with any component, the entire user interface updates, via events, to reflect the change.

This isn’t meant to be a complete implementation of event dispatching in Swift, rather a demonstration of what’s possible in Swift with protocol oriented programming. For a more complete version, take a look at ActionSwift.

Tagged: , , , , ,

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s