Protocol Extensions in Swift 2.0 – Draggable UIViews

Protocol extensions in Swift 2.0 rule

One of the features I was most excited about when Swift 2.0 was announced was the ability to provide an extension for a protocol. This means that you can provide a default implementation for an object that adheres to a protocol. Think of this like a ruby mixin!

A real world example

What does this look like? Let’s start with something simple: we want to provide a common protocol to make things draggable.  We’ll define the Draggable protocol to have the following:

  • view is is the actual UIView we want to move
  • initialLocation is the starting center when dragging
  • registerDraggability() is called when we want our class to start listening to dragging
  • removeDraggability() is the opposite, where say we no longer want our class  to be draggable anymore
  • didPress and didPan are the two functions to handle the actual pressing and panning

Normally, this would be pretty straight forward: You would create a UIView subclass that would adopt the Draggable protocol to which you’d then implement the necessary properties and functions.

This works great until you need to do this for another subview. So then you repeat: subclass, adopt and implement. All of the sudden, you’re writing what’s basically the same code over and over. That’s bad! As engineers, we want to write code that’s DRY (don’t repeat yourself) so whats our first take at rectifying this?

Composition vs. Inheritance

If your first response was to create a baseclass that adopts and implements the Draggable protocol, you wouldn’t be wrong and infact that’s a perfectly sensible approach.

Inheritance is a powerful and a tried and true programming practice that has its place; however, it is possible to get into hierarchy hell. I know I’ve run into the issue of having too many UI classes that inherit from each other and making one small change in a base class ends up affecting WAY too many of its descendants.

This is where composition shines!

Instead of having a long chain of subclasses that can be somewhat brittle, we’d like to compose our objects to adhere to our various protocols. This becomes very viable with protocol extensions as we now can provide a default implementation of a protocol:

The real beauty of this protocol extension is we’re giving ourselves access to any UIView that adopts the Draggable protocol! How awesome is that? For example, you remember that view property in the Draggable protocol that is required to be implemented? Now we can just do this:

Basically, any UIView that has the Draggable protocol automatically receives the built in functionality. So what about the remainder of the protocol’s definition? Let’s fill them out:

I don’t believe I need to go over the code to drag a UIView as that’s been covered dozens of times, but there are some caveats that I’d like to bring up:

I had to extend the UIGestureRecognizer class in order to add a method called handler. Tyler Tillage over at CapTech did an excellent job explaining why I couldn’t just use the existing addTarget: action: in the protocol extension here. Long story short:

UIKit is still compiled from Objective-C, and Objective-C has no concept of protocol extendability. What this means in practice is that despite our ability to declare extensions on UIKit protocols, UIKit objects can’t see the methods inside our extensions.

To get around this, my handler closure wraps around some object associations to store the closure which is then called on a default selector. I’ll write another post about why I had to do all of this, but feel free to check out this extension.

Just tell me what I need to do to make things draggable!

When all is said and done, we want it to be as easy as pie to make ANY UIView draggable. I feel like I’m almost there with this:

All you need to do is register the draggability on the view, and provide a storage backing for the view’s initial location before it starts dragging. Pretty simple right?

The best part of this is it can now be applied to other, UIView backed classes! How about UICollectionViewCell?

Remember, we’re not creating a single DraggableView baseclass that requires all of our other classes to subclass. We’re simply adding the additional functionality provided by the protocol and its default extension.

So what does this look like in application?

protocol extension uiview dragging protocol extension uicollectionviewcell dragging


Closing thoughts…

I don’t think I’m sold on this implementation yet. I’m not a fan of object association as some of it feels dirty but in the end it does work, pretty well at that too. The biggest limitation right now is that extensions cannot store additional values and they do not support really anything regarding selectors. Once those two features are put in place, we’ll really be able to do some even more amazing things without having to jump through loops.

Feel free to check out the repository on GitHub and let me know what you think! I’d love to clean this up more if anyone has better ideas!

Associated Values in Enums in Swift 1.2

Swift’s Associated Values for Enums are Awesome.

When I first started writing Swift full time about 6 months ago, I only had a simple understanding of what they actually were. For example, say we’re building template builder for a UITextView that has differently styled parts (think HTML). I’d start with something like this:

Nothing crazy. We want to be able to easily build a styled body of text. And it works, but it feels a little clunky. What are a couple ways we could clean this up?

  1. Create a protocol that has a property of attributes and make a bunch of classes that implement said protocol.
  2. Use inheritence
  3. Utilize associated values in Enums!

What Exactly is an Associated Value?

Associated values allow our cases to have actual inputs. Instead of the enum case returning a rawValue, we instead can allow for any number of properties to be associated (get it?) with it.

I had a difficult time (more so than I should have) initially figuring out what this actually meant, but I think the example above will prove to be super clear. Let’s change up our Enum to look like this:

What we’re saying is that (for example) in order to specify something as a Header, you must specify a string to go along with it. So what does this look like in application? We can now do the following:


What’s even nicer is that we can specify multiple associate values. Want to include an image along with a paragraph? Add it as another value. Maybe you’d like the ability to override a default styling? Have it included as an optional!

One final thing that I really like is that it really allows you to write some pretty easy to read code:

This is only scratching the surface of what they can do. We can get super tricky with implementing various protocols on the Enums. Swift 2 will also be adding in the ability to do where clause matching on the enum case’s and their associated values, so we can get even more explicit in how handle different situations.

Tic Tac Toe in Swift with a UICollectionView

I’m starting to ramp up how much work I put into using Swift to eventually switch over to using it completely over Objective-C now that Apple has released version 1.0 with iOS 8.

One of my first projects was to make a simple Tic Tac Toe game in Swift. What started out as something relatively simple, as Tic Tac Toe isn’t the most complex game, turned into something much more involved.

Utilizing standard UIKit components and implementing a MinMax algorithm to make the AI unbeatable, I set out to make a barebones, but fully functional, game of Tic Tac Toe in Swift.

Without going into too much nitty gritty detail here on my website, I’d implore you to just browse through the source code over on GitHub. I’ll lay out some of the more important parts which I enjoyed making.

UICollectionView as the Tic Tac Toe Board

Instead of manually laying out 9 buttons or interaction enabled views, I instead went with what could be considered overkill and created the board using a 3×3 grid UICollectionView. I chose to do this for several reasons:

  1. Subclassing the UICollectionViewFlowLayout is neither difficult nor scary and getting familiar with the UICollectionViewLayout protocol is pretty important
  2. The UICollectionViewFlowLayout allows you to make a grid with even spacing pretty darn easily and pretty much straight out of the box. Just make sure you have 3 sections with 3 rows each.
  3. Built in item selecting meant I could hook that into my board pretty easily:
  4. Automatically scales any any resolutions to work on both the iPhone and iPad as well as easy to customize just like any other standard UIKit control.

Keeping all Tic Tac Toe logic in the GameManager

This meant all of my display logic was handled in my UIViewController and any sort of item placing was handled in the GameManager class. One particular good example was the item placing that I showed above in #3. The if manager.placedPiece(indexPath.row, y: indexPath.section attempts to place a piece at the provided indexPath coordinates for the current player. If it’s successful it’ll return true and tell the UIViewController to change its display of whose current turn it is.

This way the UIViewController doesn’t really ever need to tell the GameManager what to do; however, the GameManager can notify the UIViewController when it should update something accordingly, like in the actual placedPiece method:

The code is pretty readable, but the last part where we reload the UICollectionView’s cell at the location given means we update the UI to display the newly placed piece if need be, instead of just reloadData-ing the entire UICollectionView. Sure – performance wise a 3×3 grid isn’t going to kill anything but this is a matter of principles, right?

The Unbeatable AI

This was a requirement that I seriously didn’t think would take that long but ended up being a lot more involved than I thought. I started out by doing my best to handle all of the cases by hand. I was able to make the AI unbeatable EXCEPT for cases when I, the user, would create “Forks” (Turns where in the next turn I’d have two ways to possibly win). Here’s the logic for the AI’s turn:

  1. Check if the middle piece is open. If it is, place it, otherwise choose a corner and place it only if it’s the AI’s first turn.
  2. Check if the AI has two pieces in a row and can place a third, and if so place it there to win (horizontal, vertical and diagonal)
  3. Check if the player has two pieces in a row and can place a third, and if so place it there to block the player from winning (horizontal, vertical and diagonal)
  4. Check for a fork – This was what I was missing and will explain in a bit
  5. Place it in the center if it’s open
  6. Place it in any free corner
  7. Place it in any free side piece

For the longest time, I couldn’t figure out how to do #4. Searching Google suggested I create a MinMax algorithm for the AI to determine which move gives it the best chances to win. I fortunately found an example of how to do this in Java, to which I then converted over to Swift.

MinMax in Swift

I’m not going to try to reexplain how the MinMax algorithm works in this instance as the link provided will do a much better job at it; however, if the score that it returned to my when checking for any forks the AI should make met a positive score, the AI would place an item there. This made the AI unbeatable!

unbeatable tic tac toe AI

Wrapping up

In the end, I was pretty happy with how this turned out! Now, if I was a good developer I’d go ahead and write some tests to make sure my logic was sound… but we can save that for another day.



UIViewController and UITableView in Swift

I originally wrote this post back when Swift 1.0 came out. Since then Apple has released several new version of Swift with new syntax. I’ve updated this post accordingly – Bay 11/13/2015

I’m just starting to play around with the newly announced programming language, Swift.

So far it’s a bit tricky to get used to the new syntax simply because when I first started writing Objective-C I had to learn some of its funky behaviors and nuances. Swift reverses a lot of those decisions and brings it inline with more modern languages.

To get started with Swift, aside from playing around in a Playground with it, I’ve decided to just start rewriting basic controls that I’m familiar with in Objective-C. To start, I rewrote what is a super basic UIViewController with a UITableView as a subview, displaying its contents.

(all code snippets are in Swift, don’t mind them being labeled as Objective-C)

Let’s declare our data source.

Next we implement the viewDidLoad method that we’re so familiar with but this time we’re “overriding” it.

Implement the two required methods in the UITableViewDataSource protocol:


And that’s it! Now we have a UITableView displaying 0 – 100. Not that useful, but it allows us to start seeing what was familiar with Objective-C in a new light.

The full code source can be found at this Gist.

Handling Bad Connectivity with AFNetworking 2

I’ve been a web developer for the past ten years. There’ve always been plenty of challenges for me while creating websites – some I’ve handled better than others. I’ve run into file submission security issues, handling vast amounts of downloads, terrible web designs, hardening servers and more. There’s one thing I never had to contemplate until I started developing mobile applications: bad connectivity issues.

With DohGames, if a user ever had an issue connecting to the site or the download, I could just chalk it up to an internet issue or some faulty setting on their router (AKA, not my concern). The vast majority of the time though, a user’s connection would be reliable enough and out of my realm of control. A simple refresh to the page, or the clicking of the button again would fix the problem.

With mobile apps, it’s a different story.

Bad Connectivity Issues Abound

Your users are out and about. They could be traveling in a car, underground, in the middle of nowheresville USA or in a super crowded city with millions of users all fighting for their connections. Connections will be dropped or a lot slower than they should be in 2014. It sucks but you have to handle it unless you want a poorly rated application.

While I don’t feel like I could sufficiently discuss the various design decisions on how to handle this all (I’m a developer, not a designer for good reason), I did run across this while working and had to implement what we felt would work best for our app.

AFNetworking to the Rescue

afnetworking-logo bad connectivity tutorial

I recently upgraded our networking code to utilize AFNetworking 2. We were previously using a completely handmade solution that was unreliable, clunky and full of boilerplate code that had to be copy and pasted every time you wanted to add a new request. It sucked.

A lot.

I could write plenty about AFNetworking (and hopefully will) so I’ll leave out all of the details BUT one of the added features of it, that I was completely unaware of at the time of making the switch, was the built in ability to handle bad connectivity issues with the AFNetworkReachabilityManager.

Every AFHttpRequestOperationManager has a ReachabilityManager associated with it. This ReachabilityManager then has a block called reachabilityStatusChangeBlock that is called whenever your device loses/gains connectivity. We can utilize this to our advantage!

The reachabilityStatusChangeBlock is called with a AFNetworkReachabilityStatus parameter which tells you’re the current state of your connection. Using this, we can tell our app to do whatever we want.

For example, inside your subclassed AFHttpRequestOperationManager (I do this inside my -(id)init), you can specify your block as follows:

AFNetworking (and I) would suggest you resume ([self.operationQueue setSuspended:NO]) the operationQueue on your AFHttpRequestOperationManager when your connection is OK or suspend it ([self.operationQueue setSuspended:YES]) when these events occur so that when the connection is fixed, any actions the user wanted to take will resume normally.

You can test this out once you’ve added it to your AFHttpRequestOperationManager by running your application, setting a breakpoint inside of that block, and toggling the AirplaneMode on your device/simulator.

What else?

That’s pretty useful in itself; however, there’s still a lot more to be accomplished with this code block! Notice how my final case in that switch statement mentions timeouts? What if the user just had a bad connection but is fine now? What if their connection is fine but your backend is running slowly? Do you reattempt? Do you completely disable the app? Let the user continue with no notification whatsoever?

This is where things can get tricky.  Let’s just say it involves implementing an attempt count as well as the ability to easily retry requests. But that’s for another day and article.

Switched over to T-Mobile from Verizon – Speedtest

I recently switched over from Verizon to T-Mobile for various reasons. While I don’t need to go into too much detail, I found the following very funny when I decided to run a speed test on my previous phone as well as my new phone:

Samsung Galaxy S3 (Verizon) and my new Google Nexus 5 (T-Mobile).

Let’s just say, getting 10x the download speeds is just ridiculous. Looks like I’ll be pretty happy with my switch.


Turns out I had renabled a very old configuration for this website that was causing things to break. I’d become frustrated in trying to debug it about a year ago and had given up.

Not sure what made me look into it again, but I was able to find out the issue pretty easily and now we’re back up and running. Time to fix all of this and clean it up.

A lot has changed in the past year and a half.

Already Used Variable Names in WordPress

Last week I handed over a somewhat completed plugin over to Kyjen, and I was pretty proud of it. I knew it wasn’t 100% done; however, it was a good first step. Earlier today, I got an email from them with a screenshot of a very weird bug:

All of the messages in my plugin were showing up in the admin/user-new.php within the WordPress Admin… Pretty weird, right?

After a lot of investigating, and trying to figure out where the hell my custom messages were being called, I came across this part within the admin/user-new.php:

Turns out, in the custom messages in my plugin, I had declared the array that held all of my messages as $messages, thus overriding the WordPress core.

Now I know to be more careful in my plugin variable naming. Previously, I had been careful with just my function names, but I guess it can’t hurt to be as explicit as possible.

Custom WordPress Admin Menu Pages

Today, while I was doing some work for Kyjen, I came across a situation that I wasn’t too sure how to handle: correctly utilizing the add_menu_page and add_submenu_page functions.

I couldn’t figure out how to have the first submenu item be a different name than the parent’s name. Let me clarify what I mean.

When you want to add a new menu item in the admin backend of WordPress, you call the function add_menu_page. It looks something like this:

This results in a new menu item called “Plugin Home” that you can now click on that will call the myplugin_functionname() function that you’ve delcared in your plugin. In order to add items within your new menu, you’d simply use the add_submenu_item, like this:

You would expect to only see one menu item, right? We’ve only declared one submenu item, “My Menu Item”, so it should be pretty straight forward… Well it isn’t. You actually end up having two menu items: “Plugin Home” and “My Menu Item”.

I understand this default functionality; however, I didn’t want it with what I am doing. I couldn’t find anything that explained how to change the first item that is listed under a custom admin menu. Even changing the two string parameters in the add_menu_page doesn’t work, as the first parameter is for the page’s title that is displayed on the actual page and the second parameter is what shows up on the actual menu. Changing the second parameter ended up changing the header, as well as the menu item.

I was able to finally figure out what the hell was going on by guessing at what other plugins had done, even then it wasn’t exactly apparent (at least not to me.)

In order to replace that first menu item with different text, declare a submenu item that uses the same page name. For example:

This caused me a bit of confusion, but let me know what you all think. Maybe there’s a more correct way of accomplishing this.

Making a WordPress Plugin

I’m working on a side project of mine and I figured I’d continue working with WordPress. I’ve started laying out the database and figuring out how the various entities will be communicating with each other. Should be a fun project.

I’ve never done anything open source and I’m a bit nervous my PHP won’t be up to par with everyone elses, but I guess that’s the point of trying things out and learning along the way.

iOS and Full Stack Engineer and a home cook in NYC.