Category Archives: Swift

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.