Ted's Blog

Thoughts on software, iOS Development and Games

iOS Testing For Protocol Extensions

The days of the Massive View Controller are long gone. With Swift, there are so many different ways you can make your code more modular and more testable. You can use MVVM, helper objects, and more recently, protocol extensions. Some of you may be new to protocol extensions or unit testing. You might be wondering how to get started with iOS Testing for Protocol Extensions. After all, protocols are neither class nor struct. You can’t simply instantiate them and start writing tests. In this simple tutorial, I will show you how to test protocol extensions in your Swift app.

This is a pretty lengthy tutorial. Feel free to follow along. You can also Download The Example Project Source Code on Github

Step 1.) Define your protocol.

We are going to create an example project where we will define a simple error type and a protocol that can turn the error into a basic dismissable Alert Controller. You will definitely want to check the “Include Unit Tests” box when setting up your project.


Once your project is setup, you will want to add a blank Swift file. This is where we will define the protocol and protocol extension that we want to test. The code below defines a protocol, “ErrorAlertRepresentable” that you can apply to any error type. As long as you define the alert message property, you can access a generic UIAlertController with an O.K. button to show your alert.

So now that we’ve got both a protocol and a protocol extension to test, let’s test that our protocol extension works as we would expect. Now I know some of you might think we would want to create an error type to conform to the protocol first, but that’s not really necessary. We can create a mock object, like a struct, and then we can make our mock conform to the protocol. The beautiful thing is that our mock can stay simple, even if everything else that implements the protocol in the app happens to be complex. Simple mocks like this are essential when doing iOS Testing for Protocol Extensions.

Step 2.) Create a struct or a class that conforms to your protocol.

This is something you will do in your test target. So go ahead and click File -> New File -> Unit Test Case Class to create a new Unit Test Case.


The default class you’ll get from Xcode will look like this:

You can get rid of the testExample() and testPerformanceExample() methods. They’re just stubs for beginners. You will also want to import your app module using the @testable directive. This gives your unit test target access to the project files you plan to test. After you make those changes, your blank test case should look like this.

Now we are ready to go to work. Within your test case class, you will want to define a struct that conforms to the protocol you want to test. You can call it anything you want. I usually call mine “SUT,” which is shorthand for System Under Test. You can also use the same name in lowercase for the instance of SUT that you plan to test. Putting all of it together, you get something like this:

You might be wondering why we’re giving our instance a bang and declaring it as an implicitly unwrapped optional. I do it to ensure that the same instantiation logic gets called at the beginning of each test and also to ensure that any previous state gets cleared at the end of each test. It’s really up to you though. You could use a let and declare it as a constant as well. Now that we’ve setup the protocol-conforming struct that we want to test, we can begin to write our tests!

Step 3.) Write your tests against your locally-defined entity.

In our case, we only have two tests we are interested in. First, we want to know that we can create a basic alert action to dismiss the alert, and that said action reads “O.K.”. Second, we want to know that the alert controller we create has the same title as the alert message property on our struct and that it uses the “generic okay action” we have defined in our protocol extension. Here is one way to test that:

If you run these tests, you will see that they pass. Although you can’t directly compare the generic okay action using XCTAssertEqual, you can compare the properties to make sure they match. You also may have decided to implement something like the generic okay action somewhere else. In that case, you’d simply call it from wherever else you had defined it (usually as a class var or a class extension on UIAlertAction).

Using your tested protocol extension in the real world

We’ve done all of the hard work to incorporate iOS Testing for Protocol Extensions. Now we can build our sample app using a real error type that conforms to our protocol. Here’s an example of a kind of error you might run into. Let’s say you are trying to figure out if something is Rick Astley. So long as the thing never gives you up, never lets you down, never runs around, or deserts you, you have a valid Rick Astley on your hands (leaving aside, of course, the possibility that your object might make you cry, tell a lie, say goodbye, or hurt you). As you go through your Rick Astley validation process, you generate errors whenever your object fails to meet one of these conditions. Your error class might look like this:

Now we’re going to define a basic validation function in a separate validator object. If you’ve used try-catch in Swift, this should look pretty familiar. We aren’t going to create anything fancy, just a simple function that takes a few boolean parameters. It throws an error whenever the object isn’t Rick Astley.

Guard statements are really useful here. They make our validation logic super concise! Whenever our “potential romantic partner” object fails to meet any criterion that would make it Rick Astley, we immediately throw an error. Now that we have our validation logic, we are going to hook up a view controller with a few UISwitches and a simple “validate” button that runs our validation logic. If one of the Rick Astley errors is thrown, we can use the new property we get from our unit tested protocol extension to display the alert. Here’s an example of how you might bring this logic into a controller.

As switches get toggled, various properties of our “Potential Romantic Partner” object change along with them. When we want to validate our romantic partner, we run a try-catch block. If we happen to catch a Rick Astley error (the error type that now conforms the protocol in our unit tests), we display the “basicAlertController” property of that error. If the validation passes with zero errors thrown, we show the “It’s Rick Astley” alert.

Simulator Screen Shot Jul 11, 2016, 8.29.55 PM

That’s pretty cool, but do you want to know what’s even cooler? You get this error alert functionality with any new error type you define. So long as you make the new error type conform to the “ErrorAlertRepresentable” protocol, the alert controller is yours! Plus, because you wrote unit tests for your protocol and protocol extension, you know it’s going to work every time. It might seem like a bit more effort to do iOS Testing for Protocol Extensions, but I guarantee you the effort is well spent. Good tests, like Rick Astley, will never give you up, never let you down, never run around, or desert you.

iOS Testing for Protocol Extensions – Source Code

All of the project files in this article are available for free: Example Project on Github

Override Launch For iOS Unit Tests

Ah, iOS Unit Tests. We all know we should write them, and yet so few of us do. Perhaps one reason we don’t is because sometimes simply setting up iOS Unit Tests is an exercise in patience itself. I encountered this recently when I wanted to add a few tests for some date logic in an app I’m currently working on. I thought I could simply add in a test case class for the one module, run the tests, and everything would be just fine. I was sorely mistaken.

The app I’m working on uses Realm as a database (which is totally awesome you should use Realm!). It works perfectly fine when I launch the app in a normal usage mode. However, when I launch the app as part of a test target, it crashes when the first view controller appears. I could have put a bunch of time into making Realm work on my test target, but I’m kind of lazy. I wanted a simple way to bypass the launch of the original ViewController. Then I could add only the tests that I’m interested in. Here’s how I did that.

Step One To Easy iOS Unit Tests – Bypass The App Delegate

I wasn’t aware of this, but there is a way to get your app to recognize that it’s being run on a test target. You can use this logic to override your App Delegate and replace it with a fake one that swaps out your initial View Controller with a dummy. You do this by creating a new Swift file called “main.swift” and placing some code like the following in that file.

So what does this do? It determines if you are in a unit testing mode, and then it swaps your AppDelegate class with a different class that you specify. In this case, I have chosen to create a totally brand new TestingAppDelegate class that only runs when I’m running my iOS Unit Tests. When you do this, you will notice a new error pop up on your AppDelegate class, right at the line where you specify @UIApplicationMain. This happens because Xcode recognizes that there are two entry points to the main application. Simply delete the @UIApplicationMain line, and you’ll be good to go. The main entry to your app will be handled by the new main.swift file.

When you roll your own main.swift implementation, you can no longer use the @UIApplicationMain directive. That's okay! Just get rid of it.

When you roll your own main.swift implementation, you can no longer use the @UIApplicationMain directive. That’s okay! Just get rid of it.

The TestingAppDelegate

This new TestingAppDelegate will be quite a lot like your ordinary App Delegate, except you can stub out the Root ViewController at launch time, thus making your iOS Unit Tests much more lightweight. Here’s how I did that.

TL;DR – It’s the same AppDelegate, except we set a blank UIViewController as the window’s rootViewController right before the application launches. Now when you run your tests, you’ll no longer see a white screen but a black screen. You’ve now made your unit tests independent of the first ViewController in your App! You can test separate modules that don’t rely on the initial view controller. This is a really helpful approach to take when you’re working in a team environment and you don’t have the time to get all of the initial view controller tests up and running. It lets you build your tests in a more piecemeal fashion. Then, once you’ve convinced your manager that the tests are worth the extra time, you can go back in and do it properly.

Protocol Oriented Programming for Games

Protocol Oriented Programming, (a.k.a. “POP”) is all the rage these days. I’ve found myself using it in all sorts of places. One of them is my own video game project – Grandfather. This is a quick breakdown of a few areas I’ve found Protocol Oriented Programming for Games to be particularly useful.

A game character carrying a key, all made possible through the magic of Protocol Oriented Programming for Games.

Put Common Animations in a Protocol Extension

When Mega Man gets hit, he flashes. When enemies get hit, they flash. As developers, we know it’s a bad idea to force all game characters to inherit this flashing animation from a single superclass. That is why we usually take a more compositional approach when designing game entities. So why not create a protocol for it?

The Flashable protocol adds a simple flashing animation to any SKSpriteNode. To give a game character a flashing animation, just make it adopt the protocol. Now when you call megaMan.flashing(), he’ll flash. When you call megaMan.endFlashing(), he’ll stop flashing. Any sprite in your game can do this!

Use Protocol Oriented Programming for Games To Make Anything Carryable

A lot of games have items. Game characters can pick up and drop items. So why not break that logic off into a protocol as well? Now anything in the game that adopts the protocol can either be a carried item or a carrier of items. Here’s one way you might do that using protocols and protocol extensions.

Let’s step through some of this logic. Carrying items typically implies some kind of ownership. Anything that can be carried is ususally carried by one sprite at a time. Carryable things also switch their category bitmasks when they are carried. In my case, I have a default implementation wherein a carried thing only collides with the floor. However, this value can be overridden by anything that implements the Carryable protocol. A key could only open locked doors when it is carried, for example.

There’s also a protocol for carrier. Carriers carry Carryable things. Makes sense, right? What I really like about this approach is the way different carriers can implement different ways of dropping and holding onto items. The holdOntoItem() function needs to be called during your carrier’s update() loop function. dropItem() can be called whenever you want your character to drop an item. In this default implementation, the item will get dropped in the direction your character is facing. Neat eh?

Make Any Scene A Side-Scroller

Ever since Apple added SKCameraNode to SpriteKit, it has gotten quite a bit easier to manage camera controls. Thank goodness we no longer need to keep track of a world node that moves as the player moves! It was super confusing. Now with protocol extensions, we can abstract some of our camera logic out of the scene. This lets us reuse our camera logic on any scene that needs to be a side scroller. Here’s how I did it on my game prototype.

There are a few ways you can make a scene a side scroller. I chose to use a camera that follows the player. The camera remains fixed on the y-axis but dynamic on the x-axis. I’ve also added two fixed cameras to the scene. When the player hits the edge of the scene on either side, we switch from the camera that follows the player to one of the fixed cameras. The transition is buttery smooth. The player never knows the difference.

With this protocol extension, you need only hook up the three cameras and the two stop points (the places in the x-direction where once the player crosses them, we switch to a fixed camera). Then simply call the updateCameraForSideScroller() in your update loop, and you’ve got a side scrolling level.

Stay Tuned to Learn More Protocol Oriented Programming for Games!

I have done a ton of refactoring in my game, using all the new stuff that’s available. I have found plenty of other uses for protocol compositions, and I’ll probably write another installment soon. This feels like the right way to build games. With Protocol Oriented Programming for Games, you get flexible pieces you can add or take away from your game elements. It lets you craft your masterpiece in a much more modular and compositional style.

Core Data vs. Realm

If you’ve done any kind of iOS development lately, you’ve run into a decision we all need to make at some point – how am I going to implement object persistence? For years and years, the only options you had were SQLLite and CoreData. Most people went with CoreData because it had less boilerplate code compared to SQLLite. By comparison it was also easier to setup.

Now there’s a new player in the game, and it offers similar improvements to your iOS development experience. Realm is a mobile database solution that promises even less boilerplate code, easier migrations, and a learning curve that isn’t so steep. Does it live up to its promises? What are the pros and cons of adopting Realm compared to other totally fine data persistence frameworks?

As a developer who is accustomed to favoring Apple’s frameworks over others, it generally feels strange to step out of the walled garden and work with a third party framework for such a generic thing that all apps need. After all, CoreData has been around for a long time. It has been battle tested in millions upon millions of applications. If we’re going to leave the walled garden, there had better be a darn good reason to do so. At the very least, we might want some evidence that the walled garden is in a state of decay and our true paradise lies elsewhere.

To drop CoreData and go with Realm is an exercise in trust. You are trusting that a third party can do a better job than Apple itself. You are buying into the assumption that Apple hasn’t done such a great job of innovating within the realm of object persistence (pun intended). In the long term, you believe said third-party will still exist in a few years time when your app and its database will likely need support and maintenance. Fundamentally, you accept the premise that Apple has failed to keep pace with current trends in mobile database architecture, and a third party can do a better job of carrying that flag forward.

Would you be correct in accepting that premise? Considering the recent decline in the overall quality of Apple’s software, it’s no surprise so many developers are ditching CoreData. Apple has its hands in a lot of different places and their limited development team is under constant pressure to keep rolling out new public-facing features every year. They’ve done all of this while inventing a totally new programming language that paves the way for the next era of programming. If they’ve been a little lax in investigating what they could do to make CoreData better for developers, it would be no shock.

TLDR; Core Data is old. It hasn’t changed that much recently. It’s still based on SQLLite, which was super hot in 2000 but has since been surpassed by faster tools. Compared to Realm, CoreData feels heavy, and for most simple uses CoreData feels like bringing a machine gun to a fist fight.

But how much better is Realm? Is it that much easier to setup? Does it fully escape the constraints imposed by CoreData, or does it follow in CoreData’s footsteps too much? How much faster is it? To what extent can it help us avoid the most time-consuming problems that relate to persistence, things like multi-threading and migration? We should endeavor to investigate each of these questions in detail.

Claim: Realm is easier to setup. It requires less boilerplate code. True or False?
True. Although Apple does go to great lengths to help you avoid writing much of the necessary boilerplate code to setup CoreData, said boilerplate code is still required. You still need the various CoreData related functions in your AppDelegate, which are generally easy to add if you’re starting a project from scratch but a bit harder to add when you want to bring persistence to an existing project. As a developer, this forces you to make some pretty big decisions about persistence right out of the gate, decisions that add weight to starting up a project.


When you check “Use Core Data,” Apple writes most of the boiler-plate code for you.

On top of this, you need to support XCDataModel files when you opt to go with CoreData. It’s not exactly boilerplate code, but it’s an extra file you need to modify just to add a single persistence-backed entity. Realm does away with all of this. With Realm, you simply install the cocoapod and subclass RLMObject. There’s no doubt about it. There’s definitely less setup time.

Claim: Realm requires less code overall. True or False?
True, especially when you include the boilerplate code you need to setup NSManagedObject contexts. A side-by-side comparison of a simple fetch request shows that Realm can accomplish in three lines of code what Core Data does in several.



Claim: Realm is easier to work with in multithreaded situations. True or False?
Mostly true, although it should be said that both are kind of a pain when it comes to multithreading. With CoreData, you have to manage a bunch of separate NSManagedObject Contexts for the different threads whereas with Realm, you need separate RLMRealm objects for different threads.

Either way, there’s some extra effort to understand what’s going on, and it often throws most developers. We were working on a project, had decided to go with Realm, and instantly ran into unexpected behavior when we needed to update some objects on a background thread. We sort of expected to be able to use the same RLMRealm object in any thread, and that wasn’t the case.

All told, I will say Realm is better at multi-threading than CoreData. It’s far easier to create another RLMRealm object than to manage multiple NSManagedObject contexts with different data merging policies (which just seem like way more than any sane developer needs to know to persist a few objects). With Realm, you will still be annoyed. Albeit less so.

Claim: Realm is faster than CoreData. True or False?
True. Realm breaks away from SQLLite and employs a number of new techniques behind the scenes to make fetch operations much faster than CoreData. This is the area where Realm makes CoreData look old, and rightly so. CoreData has been in need of an overhaul for a long time, and it still suffers from being tied to early 2000s era technologies.

Claim: Realm breaks from the major design patterns and paradigms tied to CoreData. True or False?
False. For all of the advances that come with the Swift programming language, Realm is still tied to a class heavy architectural paradigm. Just like with CoreData, you do most of the work by subclassing Object, a Realm class (Core data has you subclass NSManagedObject). This isn’t bad. In fact, it could be argued that this is exactly the sort of thing you would want. We generally want our persisted entities to be reference types because that means different parts of the app can point to the same entity. When we make changes to that entity, the changes are updated everywhere in the app as opposed to just one place.

However, for those of you who were hoping for something more lightweight, you aren’t going to find it here. In many ways, Realm follows the same patterns found in CoreData. The difference is in the total amount of code you need to write to implement your version of those patterns.

The Verdict?
I have nothing but respect for the Realm team, and not just for the work they’ve done on Realm but also the work they’re doing to engage the greater iOS development community. Lately it seems like the most informative articles on the newer Swift technologies can be found on their website. That gives me more comfort believing they’re in it for the long haul. They’ve been been hard at work bringing together a talented group of people who really understand what Swift is all about.

As a product, Realm is the easy-to-setup persistence solution we’ve been wanting. Nearly all of the things you’re hearing about it are true. Having used it in a recent project, I have nothing but good things to say. Granted, it doesn’t solve all of the headaches that come with CoreData, but it does solve enough of them to make the move worth the while. Although it can feel unsettling to leave behind a battle-tested Apple supported product like CoreData, Realm is the rare exception to the rule. It gets my thumbs up.

Weak vs. Unowned Reference in Swift

Memory management is one of those topics that seems to take a back seat to most other priorities. While each of us knows we should be doing something to make sure our apps aren’t using more memory than they should, we often find ourselves just magically trusting that automatic reference counting (ARC) will do its job even when we don’t do ours. Most of us shrug our shoulders and say, “Weak vs. Unowned References? Eh, what’s the difference?” It’s my hope that by clearing up this mystery, we’ll no longer regard Swift’s memory management system as some magical black box that “just works.” We’ll understand it and apply our knowledge to build better apps.

How does memory management work?

Everything in your app needs memory. Classes, structs, integers, enums, they all need some place to live. While one of these entities is in use, it resides in memory. Once your app has stopped using that entity, it should be cleared from memory. There are limitations on the device. There can only be so much space in memory for so many things, and every app is competing with other apps for that space. If an app uses more memory than the system gives it, the app will either slow down or come to a screeching halt, so memory needs to be frequently cleared.

For the most part, you don’t need to worry about memory management in Swift. ARC handles it for you. Usually just setting an entity to nil will cause the operating system to clear that entity out of memory.

But there are situations where the structure of your code can put roadblocks in front of the operating system, effectively preventing class instances from getting cleared out of memory when they should be. The most common of these is known as a reference cycle. Reference cycles happen when the memory management system wants to clear out a variable but something else needs it, so it can’t. If two entities both need each other, neither of them ever gets cleared from memory, and you get what is known as a memory leak (a piece of memory that can’t get reused because its data will never get cleared).

A reference cycle is kind of like the relationship between a parent and a child. Both are strongly attached to one another. Louis C.K. Once joked that as a dad, he doesn’t even get to die. Strong reference cycles work that way too.

As an example, let’s define a class that leaves open the possibility of creating a strong reference cycle.

Simply creating an instance of both a parent and its child isn’t enough to create a strong reference cycle. We need to hook them up to one another, so let’s do that.

This is a strong reference cycle. If you try to set deborah = nil, she won’t get deallocated because deborahJR needs her. If you set deborahJR to nil, she also won’t get deallocated because deborah needs her.

I say “needs,” but the underlying mechanism is more complicated than that. ARC is responsible for the memory cleanup, and ARC only cleans up a reference when nothing else refers to that entity (its reference count is zero). That is what reference counting is all about. Each time a reference to an instance of a class is created, that instance’s reference count goes up by one, and every time a reference is removed, the reference count goes down by one. When an instance has a reference count of zero, ARC can safely remove it from memory.

So now you can see how neither parent nor child can get removed from memory. The parent’s reference count will never get to zero because its reference to child can’t get removed until it itself gets removed. It’s a circular kind of reasoning that leads to both entities staying in memory forever.

Weak and Unowned references are a tool for breaking the circle and allowing one entity to get deallocated from memory. This in turn makes it possible for the other entity to get deallocated.

Weak references to the rescue!

We might reimagine the same scenario, but this time we’ll work with Kryptonians instead of children. Superman, for the most part, is independent of his parents. If they die, his super powers will protect him from the hazards of the universe. We could model it like this.

Although we have linked the two entities in a similar way, we have not created a strong reference cycle. Because Superman’s reference to his parents is weak, we can set them to nil when the planet Krypton is destroyed, and ARC will clear them from memory because their reference count is zero. A weak reference is a way of creating a reference to something without increasing the reference count for that thing.

In Swift, all weak references need to refer to optional types. They are used in situations where the entity referred to can be optional. Superman’s parents could be dead (hence inaccessible as a property), so they are declared as an optional weak reference.

There are situations where a weak reference isn’t appropriate because the thing being referred to must not be nil. In those situations, it is best to use “unowned” to denote the reference type.

A good example would be Superman’s superpowers. The superpowers are nothing without Superman to control them, and when Superman dies from Kryptonite exposure, the superpowers die with him.

We could model it like this:

This sets up an interdependency between any given Kryptonian and her superpowers. The superpowers variable on Kryptonian is declared as an implicitly unwrapped optional in order to bypass one of Swift’s requirements that an initializer cannot pass self to another initializer until all properties on the instance have been set (also known as two phase initialization). Because all of the properties on Kryptonian are either optional or implicitly unwrapped optional, they are already set when the init() method gets called, which makes self available to the Superpowers initializer.

With this setup, one need only create an instance of a Kryptonian to access the superpowers linked to him. Those superpowers also store a reference to the Kryptonian that owns them, giving us another means of access to our Kryptonian without creating a strong reference cycle. If the instance of that Kryptonian is set to nil, that Kryptonian will be removed from memory along with his superpowers just as one would expect. Superpowers need a person to command them if they are to be of any use at all.

There are other scenarios where strong reference cycles can result, and I’ve really only covered two possible solutions to strong reference cycles. Hopefully this eliminates some of the confusion surrounding weak references and unowned references. Depending on your project, you may need to use one, both, or none at all. Even if this doesn’t affect any of your current projects, you can at least sleep a little better understanding how ARC clears out memory.

Protocol Oriented Programming Is All About Object Composition

It feels like I’ve been digesting Apple’s WWDC 2015 talk on Protocol Oriented Programming for months now. It certainly seems like we are in the middle of a huge paradigm shift. After all, you don’t go switching orientations around willy-nilly. We’ve been doing object oriented programming for decades, so the declaration that we are moving away from it can only be seen as a rather bold one.

But although the language surrounding the new paradigm seems grandiose, the changes themselves aren’t. It’s simply the culmination of the goals Objective-C originally set out to accomplish. By emphasizing design patterns that do not require subclassing, Objective-C distinguished itself from C++ as a language that favors object composition over hierarchical class inheritance. We are not entering some new age of Protocol Oriented Programming. The new developments in Swift merely cement familiar patterns and ideas we have been embracing for almost as long as we’ve embraced OOP.

Protocol Oriented Programming is one more way of achieving a composition-based architecture. It emphasizes “has-a” relationships over “is-a” relationships. With classes, we are able to inherit functionality by virtue of an object being a kind of thing. Now with protocol extensions, an object can inherit methods and variables by virtue of having certain things.

For me, the problems of strictly hierarchical design and class inheritance became pretty clear when I was working on my random trick generating apps. I had a base class for all types of Tricks.

And then from there, I created different subclasses for each different sport. Because each sport has its own dedicated app, this felt like a natural way to draw a line between each product.

I created something like this:


But even within the different trick-based sports, there are other sub-types of trick. Skateboarding has its own set of rail tricks, snowboarding and skiing both have their own kind of jumping/aerial tricks. BMX has some combination of each as well. So you keep you subclassing to these subtypes.

The interesting thing starts to happen once you go down a few levels in the class hierarchy. That’s when parallel subclasses start to have the same properties in common with one another. For example, both SnowboardJumpTrick and SkiJumpTrick have degreesOfRotation in common (how much your body spins around while you are in the air). They also have grabs in common.

A programmer might want to add a function to both of these types, something that depends on the type having degreesOfRotation. In my case, I wanted the app to randomly generate some multiple of 180 between zero and any other multiple of 180 (540, 720, 900, etc.) because in both sports nearly all of the aerial tricks are built from combinations of half-spins.

To solve this problem, one might try an inheritance-based approach where you move degreesOfRotation to some superclass that both Snowboard Trick and Ski Trick inherit from. It might look like this.

Although adding another tier to the class hierarchy kind of solves our problem, it introduces several new ones. The jump tricks no longer need to declare degreesOfRotation, and can also inherit our random 180 spin generator function, but we’ve now shoe-horned that function onto the more generic SnowboardTrick/SkiTrick as well as anything that subclasses them. In an effort to share functionality between two classes that have the same property in common, we have created a more bloated and complicated class hierarchy that’s harder to understand.

Object composition tells us we should almost always avoid doing this when there are better options. Before protocol extensions, you could favor composition by creating a helper class that does the random 180 spin function for you and then having both Snowboard Jump Trick and Ski Jump Trick call that function whenever they need to generate a random multiple of 180. It would look like this.

You can see how this solves the problem of adding the shared functionality while also preserving a more flat class hierarchy that’s easier to understand. There’s no need for a bloated base class when we can create tiny components that each of our entities can share.

Protocol extensions extend this idea even further. Instead of making Rotatable a class, we can make it a protocol that both SnowboardJumpTrick and SkiJumpTrick adopt. Then we can extend the Rotatable protocol to add the random 180 degree spin function to anything that adopts that protocol. If we declare both SnowboardJumpTrick and SkiJumpTrick as adopting the Rotatable protocol, they both get the random 180 spin generating function.

This is really cool because it now appears as though both classes (which exist in separate hierarchies) have inherited the same method. More importantly, we’ve done it all without creating any new subclasses! The protocol extension gives us the ability to grant new functionality to two separate entities that have the same property in common. It’s “inheritance” by virtue of a “has-a” relationship as opposed to “inheritance” by virtue of an “is-a” relationship.

For all the talk, you’d think we were entering some new age of programming. Although Swift does change the game dramatically, protocol extensions are merely another way for us to build apps that favor object composition over hierarchical class organization. By giving equal weight to another kind of “inheritance,” Swift 2.0 makes official an axiom that many programmers have known for a long time; Build flexible components and subclass sparingly.

Action Sports Dice Apps Progress

The latest iteration on the Dice Apps concept is available on the App Store. I have a added quite a few new features to the products and also corrected some of the architectural mistakes we made when we first set out to build the product.

What’s new?

-Apple Watch Companion App with “Trick of the Day” watch face

-More tricks in each of the apps

-New difficulty modes

-Force Touch Trick Dictionary

A Unified Code Base

First off, the code is far more generic now. In the first few versions, we had different projects for each dice app. It seemed like a good idea at the time, but that’s really not the level of granularity that makes sense for an iOS project that shares so much code between the final deliverables. Ideally, what you want is a single project with multiple targets, each representing a different product you plan to put on the App Store. So that’s what I did.



With a setup like this, you get a lot of benefits with fewer headaches. In a nutshell, it’s more maintainable. You can have a single Github repository for the entire codebase as opposed to multiple repositories for each project. At first, I thought an XCWorkspace was the thing I’d need, but that’s one level higher than something like this. It’s more for multiple projects that share frameworks. This is a single project with multiple targets that share code, so sticking at the level of the project just makes more sense.

The only thing that gets kind of annoying is Apple’s limit on the number of build schemes you can have in the upper pull-down list. I think I’ve maxed out the number of targets, meaning I have to create a new scheme for some apps that I’ve built previously. It’s a bit of a headache, and I’m sure there’s some better way to do it, but it seems to be okay for now.

So Many Targets

There are probably more targets here than you’ll ever encounter in a single iOS project. That’s because I decided to make every app available on the Apple Watch, which effectively creates two additional WatchOS targets per iOS target. Since I’ve also created additional targets for each free version of each app, you end up with a whopping six targets per app. I have 4 sports I’m currently *ahem* targeting, so that’s a solid 24 targets in one project alone.

Now I’m almost certain I’ve made some kind of mistake as it seems like Apple doesn’t exactly want a single project to build this many targets (otherwise they would have designed for it). However, I ran into some unique constraints, and one of them is the Apple Watch.

Frameworks are OS-Specific

Had I been initially aware of this issue, I would have wasted a lot less time trying to cram everything into an iOS framework only to discover that I couldn’t port my models to WatchOS. After a lot of time spent fighting the system, I decided that the notion of a framework just didn’t fit what I was trying to do. There was too much code sharing between iOS and WatchOS, and because you can’t build a framework that can be deployed on both, I had to abandon it.

(I did end up creating a tiny framework later on, but it only applied to iOS and carried a few custom views that are shared between all iOS targets.)

I learned a lesson. If you plan to share your models between different operating systems that Apple supports (iOS,MacOS, WatchOS), you won’t be able to put your models into a single framework that can be deployed to all of your targets. This seemingly gives you two options.

1.) Create view controllers / views that are ignorant of your models and that refer to more generic foundation type classes, and put those into a framework that can be used in all of your apps.

2.) Abandon the idea of adding your view controllers to an iOS framework, keep the code mostly the way it is, and manually give the classes membership in the appropriate app targets.

I went with the second option. There’s probably some third option that I’m currently not aware of.  There comes a point (usually 11:00 P.M. for me) where you sort of give in and go with what works. With my setup, I still got most of the things I was looking for: A.) The ability to build all of my apps by subclassing a few generic view controller and model classes. B.) Sharing the same models on iOS and WatchOS.

One Storyboard Per App

This can be a point of contention among iOS developers. I’m certain there are those who will lambaste me for using multiple storyboards and taking this approach, but in retrospect it really wasn’t that bad.

Each of my iOS targets for the dice apps has its own storyboard. That means Skate Dice has a different storyboard than the free version of Skate Dice, which ultimately has a different storyboard than Snow Dice and Snow Dice Free. They share mostly the same code with the exception of a few subclasses to handle upgrading from the free version to the paid version.

Now generally this goes against the notion that you should have a single place for everything, and although I strongly agree with that premise, I don’t think we should totally throw out having the ability to visually mock up a design just to achieve single-implementation zen. There’s a tradeoff. I like to see what I’m designing, and if that means having a duplicate storyboard for a free version of an app, I’ll happily bite that bullet.


There are a few reasons why having multiple storyboards ain’t so bad:

1.) It’s not like you have to redesign the view controllers from scratch. You can actually duplicate the entire storyboard, give it another name, and add it to the new app target. This takes less than a minute.

2.) The new storyboard becomes the place where you tell the system which new view controller subclasses you’ll be using. My free apps subclass the view controllers in the paid apps to prevent non-paid users from accessing the more advanced features. Those subclasses are set in the free version target’s storyboard.

Towards Genericity

I’m usually not a fan of buzzwords like that, but it’s one that helped guide my development of the dice apps in this latest iteration of the products. I kept thinking “how can I make this more generic.” Usually that means taking some function you see in a subclass and finding a way to move it to the superclass so you don’t have a duplicate implementation of the same function, but it can go beyond just that.

In my case, I realized one of the biggest mistakes we made from the very beginning. We chose to use pre-rendered graphics for the dice pieces. That means if we wanted to add a new trick to the apps, we’d need to commission the work of a graphic designer, have that person lay out the text on a dice graphic, and give us the final dice piece in the form of a .png file.

In other words, monumentally wasteful and stupid. I wish I could reach back and punch my 28 year old self.

Thus in this iteration I took it upon myself to create a generic dice piece with three auto formatting lines of text that use the appropriate font. It worked surprisingly well, and as a result the graphics in the app are much smoother.



I initially thought I may have needed to create multiple UIView subclasses to handle this task, but Apple’s Stack View class did a wonderful job for me. When you hide one line of text, the other lines of text grow to fill in the space. Plus, if you turn on autoshrink, the font size will shrink as the text gets to the left and right edges of the dice piece. Add in a few auto layout constraints, and you are good to go!

Once that was done, I built a little framework around it and added it to all of the app targets. Now the text renders cleanly and beautifully in all of the apps, and we get the added benefit of being able to add in any new tricks we want (no need to tie up a graphic designer with hours upon hours of monotonous dice graphic work).

What’s Next?

Now that the codebase is generic enough to let us add in any trick we want, all kinds of things are possible on a relatively short timescale.

1.) More dice apps – With this codebase, it’s easy to kick out Wakeboard Dice, Parkour Dice, Gymnastics Dice, or any sort of extreme sport procedural trick generator app in a matter of days.

2.) Let users create their own tricks – There are tricks we probably haven’t even thought of, so if something is missing, why not add it yourself?

3.) Context-specific slopestyle mode – Our current Slopestlye Mode only handles generic terrain park features like jumps and rails, but since we can add in any trick we want, why not have down rails, flat boxes, hips, quarterpipes, all in a line?

It’s all very exciting, and in a way, funny to me. I sort of thought we were done a few years ago, but as I spend some more time working on the product, I realize we were just beginning.

Two Ways To Detect A Doomed iOS Project

As a contract iOS developer, I am frequently sent in to do damage control after someone’s offshoring didn’t quite go as planned. The previous developer put on a nice little magic show, but the code behind the curtain turned out to be little more than smoke and mirrors. I always feel a strange mix of empathy with a tinge of righteous indignation when this happens. That’s what you get for going with the cheapest person you could find! But even that’s not 100% correct. I know people who charge more than what I charge and still deliver unworkable crap.

In any case, you are in a bind. You want to be technical enough to know what your developers are actually building, but it takes a while to get that knowledge. That’s why I’ve prepared a little checklist so you know what you should be getting and how to identify those things when you look at an actual Xcode project (which you should always be doing!!!).

Here are the two signs your iOS project is doomed.

The code isn’t MVC or MVVM or Modular in any sense.

There is one design pattern that trumps all of them, a design pattern that when applied correctly will determine the fate of your project. Model-View-Controller. Say it again. Model-View-Controller.

Now what does it mean? MVC is a way of designing your app so there’s a nice separation between the things that represent data (people, blog posts, timecard entries, likes, etc.) and the things that show the data (image views, text fields, screens, etc.). In other words, the thing being modeled (i.e. that data in your app) needs to be separate from the thing showing that model (i.e. little rectangles with images in them, labels, etc.).

Why is MVC important?
When your developers follow MVC, it makes your code more reusable and portable. It also makes your project more flexible. Code that’s used in one part of the app can be used to add features to another part of the app. If someone designs a really cool screen, it can be repurposed to show off other kinds of data somewhere else. Or if someone creates a nice clean job post model, it can be reused in a number of different screen layouts. As a software nerd, I love this kind of modularity. Your engineers should be equally excited about it.

How to tell if your code isn’t MVC
One telltale sign is a small number of files when you open your Xcode project. If you see just one file representing a thing called a View Controller, and nearly all of the code is stuffed into that file, there’s a 100% probability your developer isn’t following MVC. Ask your developers “where’s the class representing the model?” If they can’t point it out to you, or they get defensive, don’t work with that developer.

Another telltale sign is a very messy .xib or storyboard file. If you see something like this, where it’s not clear what the screen is supposed to represent (because crap is layered upon crap), it means your developer didn’t know how to create separate screens, so he just created a single screen and crammed everything into it. You’d think I’m joking about this, but I’ve had enough bosses and contractors do this kind of thing that I feel like I need to point it out. Run!

Good projects that follow MVC tend to have the code broken up into a number of different files representing objects that are neatly organized in a way that makes sense. Ask to see these objects, and ask your developer to create a chart showing you the relationships between them.

There’s no local data store

This one isn’t necessarily a deal-breaker, but if your app connects to a server, you will absolutely need a local data store of some kind at some point in the development process. This is not debatable. It determines how responsive your app will be. It is the “special sauce” behind a great user experience.

Although the data for your app is on the server and you could technically make your users go to the server to get data every time there are posts or likes or work orders, these are mobile phones for crying out loud! Internet service goes in and out. There’s never a guarantee that your users will be able to access the server all the time.

To compensate for this, your developer should have used a local database. The local database holds onto things your users have downloaded from the server. If the data are relatively fresh, there’s no need to make your users wait to get the data they want when they tap on stuff. You can just show them what you’ve already got while the app syncs data from the server in the background (silent but deadly UX).

Have you ever seen apps like Facebook and wondered how they’re so clean with so few spinning wheelie indicators? Yeah, that’s because they’re using a local database. If you feel like your app has too many of said spinning wheelie indicators, or said spinning wheelie indicators seem to stay on the screen too long, it’s probably because there’s no local database.

How to tell if you have no local database
If you’re working in iOS, you should be using Core Data or Realm. Look for a file with an extension .xcdatamodeld in your Xcode project, or look for a framework called Realm/RealmSwift. Also do a quick search for the term “NSManagedObject” or “Realm.” This search should pull up a few files with this term toward the top.

Most of the entities you find in your search will be data model objects. They represent the data in your app that is backed up on your local database. Remember that section on Model-View-Controller? Read it again. If you see lots of NSManagedObjects (Object if your developer used Realm), it’s a good sign of overall code health. It means your developers are probably following MVC and keeping a local copy of data taken from the server.

Like Martha Stewart says. It’s a good thing.

Look at the code
There’s no need to be intimidated by the code. If you’re managing the project, you should be looking at it pretty regularly. You don’t need to know everything about what’s going on in there. You just need to see enough to know you’re not dealing with a $10,000 train wreck.

You’ll actually be surprised at how graphical Xcode is. For years, Apple has been trying to push this idea that designers can use Xcode alongside developers. That’s why we have storyboards and Image Catalogs. Even those fancy .xcdatamodeld files for Core Data are meant to be viewed with a graphical editor. Don’t worry. You can click on them. They don’t bite.

Naturally, these aren’t the only two signs your iOS project is doomed. There are many more, too many to make for a concise blog post that nails the low-hanging fruit. Offhand, you should be looking for Autolayout usage, no 3rd party code with “all rights reserved,” and web service code that doesn’t just grab everything from a table on the database.

As the project leader, it is your job to take an active role in managing your developers. Know what good software design looks like, and understand that just because your app appears to be working today doesn’t mean it’s built on a solid foundation that will make it easy to build new features tomorrow.

Pay attention to these red flags. Talented developers will appreciate you for it.

Finally Updated Skate Dice iOS App

It has been nearly two years in the making, but we finally got a chance to update our most popular iPhone app, Skate Dice.


The changes weren’t at all drastic. We weren’t trying for that. We simply wanted to overhaul the older graphical style. When we first launched the app, fake glosses and 3D effects were all the rage. This was before iOS 7.0 stomped in and changed all of that.

For reference, here’s our old icon:


Which, much thanks to Nick Gladding, now looks like this:



What’s involved in updating an iOS app after four years?

In short, lots and lots of compiler warnings and deprecations. When you open the project, you’re just swamped with them. It’s a natural human instinct to freak out and close everything, but don’t do that. Just take a deep breath and start addressing them. You’ll find out that most of them really aren’t that bad. With Skate Dice, I was particularly worried about some Game Center Turn-Based Match deprecation problems. I thought I’d need to learn a totally new way to implement what we had already built and tested. It turned out I was wrong and simply needed to replace one command with another in a few different places.

With so many compiler warnings, it’s best to just roll up your sleeves and get to fixing them. If it at all possible, resist the urge to dive in and completely refactor the app. You should go in with a very particular goal in mind. In my case, that goal was simple. I just wanted to replace the old graphics and animations with some new ones. If I could just do that, it would be enough. Of course, after two years, “just” switching out the graphics turns out to be much more involved. I had to implement autolayout on all of my view controllers, and I had to replace the Create A Line mode’s old scroll view implementation with a much more clean UIPageViewController.

It’s just a dice app. An update should be easy, right?

Yes and no. Technically, it’s called Skate Dice because that is the name that resonates the most with our customers. But behind the scenes, there’s quite a bit more going on. Create A Line mode requires a data model that can conceptualize a string of tricks that have to flow from one trick to the next. In Skateboarding and Snowboarding, it’s possible to land with the opposite foot forward (i.e. landing switch), so we needed to come up with a data model that can randomly generate tricks based on the tricks that came before it. On top of that, we had to build a system to interpret those tricks in a nice and clean visual format to present to our users. With Create A Line mode, people need to quickly swipe between one trick and the next.

Skate Dice also has a unique turn-based game mode called the Game of S.K.A.T.E. (available as an in-app purchase). You can challenge your friends by signing into Game Center. You take turns trying random tricks and passing them to one another. If you can’t do a trick that another person can do, you get a letter. The last person standing wins. Needless to say, I wasn’t going to release an update to the app without fully testing this feature and confirming that it is still working as intended.

I also decided it’s a good time to add in some crash reporting and analytics software, so I did a quick Fabric and Flurry install. Now we can get a sense of what’s causing our app to crash as well as how many users are interested in upgrading to the full version. It’s also fun to see what kinds of difficulty settings people prefer. There’s raw data out there that nobody has captured before.

Old screenshot:


New screenshot:


What’s next?

Aside from updating all of the apps to the new graphics style, I’ve been giving a lot of thought to using iAd on the free versions. I’ve generally been hesitant to do that, but the fact is we need to make more money to afford all this effort we’re putting into development. I want to work on an Apple Watch custom complication for Skate Dice that comes up with a random trick right on your watch face. I also want to develop a more generalized trick trainer app that learns what tricks you’re good at and offers the best suggestions to improve your skills. In order to do any of these things, we need a somewhat bigger revenue stream. Ads on our free apps could help us accomplish that.

All told, the updates were much needed. I’m hoping the new graphical style will keep them humming along for the next four years.

Download Skate Dice : Skateboarding

Lessons from launching my first iPhone app

So I guess technically I’m an entrepreneur. I tried to escape it, but this is just in my blood. About four years ago, I was weighing whether I should go to graduate school or keep working on an app idea I had. Little did I know, the app idea would blossom into a successful product that continues to pay me and my partners to this day. Along the way, I learned a few lessons about launching iPhone apps, things I’d like to share with people who find themselves in a similar situation.

Take Small Focused Steps
Some people may or may not know this, but I wrote the entire engine for Snow Dice in a single morning. That might sound crazy, but it really isn’t when you think about it. The game is little more than a wrapper around a random number generator. All I had to do was introduce a bit of snowboarding to the random numbers, and off it went.

Prototypes don't have to look good to get people excited!

The very first version of my Snow Dice App. I wrote the code in a single morning.

My point here is pretty simple. Your idea doesn’t exist yet, but it can inch itself ever so close to existence if you just put in a few hours making something. I managed to build a quick prototype that I was able to take to the mountain that afternoon. I showed it to a few people, talked about it, and got a sense of whether it’s something they’d like to use.

Which brings me to my next point…

Secrets are for losers
When you’re trying to create something from nothing, you need to know if there are people who would like to use your thing that doesn’t exist yet. How do you answer that question? Well, you have to build something, and you have to show it to them. That means you need to trust that they aren’t going to leave their job and their family to go build your idea behind your back.

Starting a business is a social endeavor. I should know. I’m as introverted as it gets. It’s totally a weakness of mine that I’m constantly fighting. But in the early stages, you’ll have no idea whether someone likes your app unless you tell them about it or show it to them.

When I showed Snow Dice to my friends, I immediately got a positive reaction. That’s how I knew it was worth pursuing further. It led me to build new features and reach out to others who helped refine the app even more.

Don’t compete. Make friends.
Life has a funny way of creating coincidences. My version of Snow Dice was the very first on the App Store… at least for about three days until a competitor’s product showed up. Let’s just say the morning I found out about that wasn’t exactly pleasant. I was yelling at my monitor and going into Internet rage commenting about how much the other guy’s product sucked.

Guess what? That guy’s my business partner now. I reached out to him and we met up for a beer down in New Zealand. It turns out he wasn’t exactly happy with his developer, and he wanted to build a much more fully-featured product like the one I had in mind. We teamed up and used his media connections to build up a bit of hype before relaunching the product.

Try to make your product more generic
I’m a snowboarder. It’s just my thing. I love to hit jumps and go upside down. I’m also kind of a skateboarder, but I’m not that good at it. I just do it for giggles.

My first product idea was Snow Dice, but we ended up launching Ski Dice, Skate Dice and BMX Dice. Out of all of those products, the most popular is Skate Dice. Simply put, there are far more skateboarders in the world than there are snowboarders. Plus, you can skate all year round. There’s a very low-cost barrier to entry for skateboarding, making it an ideal target market for something like a random trick generator app.

Do you see what I just did there? The product I created isn’t Snow Dice. It’s the random trick generator with difficulty settings. It’s the thing that helps you come up with new things to try when you’re out doing your sport of choice.

When you think of your product in more generic terms, you open up the door to all kinds of markets and expansion. Always try to take a step back and see if you can apply your idea to another segment of the market. You might find a product that’s ten times more successful than your original idea. We sure did with Skate Dice.

Try to think on a bigger time scale
If you had asked me how much money my apps were going to make when I first came up with the idea, I would have told you they’d maybe get a few thousand dollars. Let’s just say they’ve made much more than that amount, and time is a pretty big reason why.

I initially thought the sales would die down after the first few months. Boy was I wrong. They’ve actually remained steady over the years, sometimes increasing certain months. Looking at the charts and graphs, there’s a good chance they’ll continue to sell for the next four years. That’s why we’ve decided to update their look and feel. We think they’ll continue to keep selling.

Not too shabby after a few years of on and off work!

Not too shabby after a few years of on and off work!

Don’t get tangled in bureaucracy
Every one of my partners has a share in the revenue generated. In the early stages, it enabled us to build the product without taking a huge financial risk on it. It also let us work as a team. Nobody needed to approve any budget for us to hit the ground running. This helped us utterly destroy the competition.

Why, you ask? Most of our competitors had hired developers at a fixed price cost for the project. Once they had shipped their product, it was a huge contractual ordeal to get a few changes made to their apps. They had to agree to the changes and find a price to get them done. This often took weeks, and nothing usually came of it.

This is one of the reasons I charge by the hour when I do contract work. It puts me on your side. It frees me up to simply look at your app, add your new features, and get your product out there before your competitor does something similar.

It always blows my mind when small companies add a bunch of bureaucratic nonsense into their work flow when they should be using their scrappiness to their advantage. If you’ve got a small team, you should be able to turn on a dime and get a new feature out in a few days, not weeks or months. We were able to do that, and it’s a big reason why were successful.

Remember, this is hard
Submitting an app is hard. There’s just no way around it. When I built Snow Dice, I didn’t know anything about Objective-C. I totally winged it. My code sucked. I went through provisioning hell multiple times. I ran into problems that gave me many restless nights.

But goddamn if I didn’t see that ship through. We stuck with it when times were tough and our customers were saying negative things. We listened to their feedback and gave them a better product. We lasted through one competitor after another poaching our ideas. We did it because we just care more about the product than they do.

It’s gonna be tough. This is different from any normal job you’ve ever held. You don’t get to leave at 5, and it’s gonna consume a few weekends. If you like to work this way, more power to you. If you don’t, it’ll be a rude awakening. This is the sort of dedication you need to have to see it through.

In the end, it’s totally worth it. My apps launched my career. I’m still super stoked to see videos of people playing with Skate Dice, or podcasts mentioning it. I love knowing that there are people out there using something we created. We’ve gotten more than 80K downloads, and it keeps going up every year.


This kind of thing will change you on a deep level. It’s something you can’t take back. You’ll have a hard time relating to people who haven’t done it, and that’s totally okay. You just have to continue to be yourself.

Remember this is hard, and it isn’t for everyone.