DRY Fusion data munging kata in Swift

I worked through one of Dave Thomas’s programming exercises, called a kata, and pushed my Swift 2.2 code to GitHub. The code shows how to apply the Don’t Repeat Yourself (DRY) principle to two similar but different data processing programs.


The end result of this exercise is a satisfyingly readable higher-order function, which is similar to a template method but does not require subclassing to supply context-specific logic.

Here is the kata:


And here is my implementation of the kata’s third challenge:


This was a great learning experience!

Posted in Swift | Tagged , | 1 Comment

Creating an iOS Wizard UI in Swift

I published a reusable framework, written in Swift, for implementing the Wizard UI design pattern, named Wizardry. It simplifies creating a user interface composed of multiple view controllers that enables the user to complete a task. This is a particularly important UI design pattern for mobile apps due to the small screen size.


Over the years I have built wizards for several applications, on various of platforms and with different languages. The design approach seen in Wizardry is the culmination of these efforts, with a simple, clean API that I hope developers find intuitive and complete.

Wizardry’s README file explains how to use it to build your own wizard. For a complete example, refer to the demo project.


Posted in Swift | Tagged ,

Stones on a beach

Suppose that you arrange stones into a spiral on a sandy beach.


After meticulously arranging your stone spiral, the world seems hell-bent on destroying it. A dog steps on some of the stones, a big wave carries some of them away, and a child throws part of your spiral into the ocean.

There are many ways to form a spiral with those stones; countless millions of arrangements that enable someone to perceive a spiral on the sand. However, there is an almost infinite number of ways to arrange those stones that do not form a spiral. The odds are overwhelmingly in favor of your creation losing its spiral-ness simply because there are so many more non-spiral arrangements.

Now suppose that each stone is a tiny piece of a computer program. Like the stones, the individual parts of a program are carefully arranged to induce an emergent phenomenon. Instead of a spiral emerging from stones and sand, features emerge from logic and state.

The unpredictable world in which we live indiscriminately nudges our creations toward chaos. Features break because of minute changes made to those tiny pieces of the program.

What can and should developers do to defend their creations against unceasing entropy?

Posted in Thoughts, Uncategorized | 8 Comments

Find keys by value in Swift dictionary

Here’s a helper method that might come in handy when working with a Swift dictionary. It finds every key mapped to a particular value.

This is similar to the allKeysForObject(_:) method of NSDictionary, but it is generic so it can return an array of properly types keys, instead of an array of AnyObject.

Posted in Swift | Tagged

Striving for excellence as a software developer

I’ve been a professional software developer for over a decade, and have been writing code since I was a kid. Over the years I have read a lot of advice from software developers with far more experience than me, to expand my thinking and perhaps avoid some mistakes that they once made. Some of my colleagues at various companies have been invaluable sources of insight, as well.  I’ve had enough experience at this point to learn more than a few lessons of my own, some the hard way. I want to give back, and share what I’ve learned with others.

There are basic common sense things about how to write good code that seem obvious once you know them, but are not so obvious to people who have not yet learned those lessons. Some excellent advice is repeated so often that it seems like a cliché to even mention (encapsulation is good!).

I increasingly appreciate the importance and benefits of my received wisdom very gradually. The more code I write and fix, year after year, the more these basic principles of software craftsmanship resonate with me (no seriously, encapsulation really is quite good!)

Many thoughts about what it means to write good code flutter around inside my head. In order to structure these thoughts into something coherent and meaningful I’ve started a living document on GitHub, titled “Sustainable Coding“.

Note: I strongly hesitated to use “sustainable” in the title because it is a popular buzzword. I generally consider the presence of buzzwords to be a warning that something lame is afoot. But, as I explain in the introductory section, it truly is the best word I can find that fits my needs.

If you’re interested in reading my take on what it means to strive for excellence as a software developer, here’s the link:


This document is a work-in-progress. There’s a lot more that I want to write about, but I’m not in a rush. The document will grow at its own pace.

Posted in Sustainable Coding | 4 Comments

Finding unused resource strings in an iOS app

If you work on an iOS or OS X app that uses Strings files to store localized display text, over time those files can accumulate entries that are no longer used. Perhaps a developer forgot to remove a resource string when refactoring a view controller, or rapidly changing requirements caused a flurry of changes to display text that was never properly cleaned up. If you share my obsession for having no unused or unnecessary things in a codebase, check out my new tool that finds these abandoned strings.

I posted this simple tool on GitHub, along with some information about what the tool can do and what it cannot do.


Just pass the root directory of your project’s source code as a command line argument and wait a few moments while the program does what would take an OCD-enslaved developer hours to accomplish by hand!

Posted in Swift, Tips and Tricks, Uncategorized | Tagged

Creating Tic-tac-toe in Swift: User interface

This blog post is the third and final update about my Tic-tac-toe game, written in Swift. The source code is available on GitHub:


The app now has a user interface, which allows you to play against the computer or against another person on the same iPhone.


In my article about the Tic-tac-toe gameplay and data model I presented a diagram of domain components, such as the Game and GameBoard classes. The article about artificial intelligence reviewed a perfect-opponent strategy implementation. Now that the app has a user interface which ties these components together, we can see how they fit into the bigger picture.


The containment relationship between Game and GameBoard (i.e. a Game has a GameBoard) is mirrored by GameViewController and GameBoardView. When GameViewController begins a new game of Tic-tac-toe, it creates a GameBoard used as the data source for both a Game and GameBoardView.


The state of a game is visually depicted by GameBoardView. That UIView subclass relies on GameBoardRenderer and GameBoardLayout to perform drawing work.


As the code comments above indicate, creation of the layout and renderer objects is delayed until drawRect(_:) is called to ensure that the view’s graphics context and size are valid. Each object has two properties; one with an underscore prefix to store the object and another, without a prefix, that creates the object when necessary. This is similar to having a custom property accessor that uses an instance variable, in Objective-C.

The rendering work is performed by GameBoardRenderer:


All of the rendering routines are defined in a private class extension:


This code might seem odd if you have experience with CoreGraphics, which is an API of C functions and structures. Thanks to Swift’s all-encompassing support for adding methods to types, I was able to create this wrapper API to hide the ugly details of using CGContext.


Rendering a user interface does not, and should not, involve determining the size and location of each thing in the user interface. This separate responsibility is often referred to as layout calculation. I separated these two responsibilities by having the renderer rely on GameBoardLayout for the size and location of every user interface element. The rendering methods seen above use these properties of a layout object:


These properties are all lazy in order to avoid calculating their values more than once. This optimization is appropriate because a layout object is used multiple times throughout a game.

There is a lot more going on in this app, so if you’re interested be sure to clone the repository and dig in!

Posted in Swift, Tic-tac-toe | Tagged , | 1 Comment

Higher-order functions in Swift

This article reviews some very useful higher-order functions available in Swift’s standard library, by showing a simplified implementation of each function. Along the way, I’ll explain how all of the higher-order functions are based on a single loop.

Let’s get higher

Similar to how a rock guitarist’s style can be influenced by listening to jazz, Swift is influenced by functional programming. One of the key functional contributions is polished support for higher-order functions.

By definition, a function is “higher-order” if it has one or more parameters that are functions and/or if it returns a function. In Swift, “passing a function” really means passing a closure, which is the name for an executable block of code. For example:


The textbook definition of higher-order functions does not suggest how mind-altering it can be to use them. This might not seem like a big deal, but using higher-order functions to process sequences/collections, instead of writing loops, can lead to a new and arguably better way of thinking about data processing. It allows the developer to stop thinking so much about how something should happen and, instead, focus more on what should happen.

Let’s look at simplistic implementations of commonly used higher-order functions in Swift. I’ll show you how they are all based on the reduce function, which itself relies on a single loop.

The code reviewed in this article is available here.

Note: Never use my implementations of these functions, they exist only for explanatory purposes. My functions assume the input and output collections are arrays, for simplicity. My functions are not at all optimized. The standard library methods are much better than mine, so use them instead.


The most versatile function reviewed here is reduce. Reducing a sequence means transforming many items into a single item. For example, an array of integers could be reduced to the sum of every integer in the array. In this case, a sequence of integers is reduced to a single integer.

An interesting caveat, however, is that the resultant “single item” can itself be a sequence of items. After all, an array is a thing unto itself, despite the fact that it might contain other things. We will see this caveat put to use later.

As I explain here, reducing a sequence involves an accumulator. The accumulator is initialized to a default value, and can be updated when “combining” each element in the sequence.


This function uses a for-in loop to iterate the sequence and combine its elements into a single item. When you use reduce or any of the functions based on it, you’re reusing that loop instead of writing a new one. In a sense, higher-order functions that operate on a sequence enable a form of code reuse that avoids loop duplication.

Here is how reduce can be called:


Note that I’m using trailing closure syntax for the closure argument. That closure is the combine parameter.

All of the other higher-order functions that process a sequence can be defined in terms of reduce. Let’s check out how…


Taking a subset of items from a collection is a very common programming task. It involves making a yes/no decision for each element in a collection, to determine what to include in a new collection. The filter function handles all of the implementation details except for deciding what the output should contain.


This function reduces the input array to an output array by consulting the include closure for each input element. That decision-making logic is provided by the code which calls filter, such as the “is even number” logic in the above example.


The map function performs a one-to-one transformation from an input sequence to an output sequence. The output type can differ from the input type.


Once again, the reduce function is used to implement a higher-order function. As this example shows, mapping a sequence is another way of “reducing” it.

Here’s a more enticing example. Suppose you have an array of Customer objects but what you need is an array of each Customer’s uniqueID property value. You could create a mutable array, loop over the Customer objects, and add each Customer’s identifier to the array. Or you could transform the customers to their identifiers with one simple line of code, using map. Here’s how that might look using the Swift standard library map method.


This example uses a shorthand argument name ($0) to refer to the first argument passed into the closure, which is a Customer object.

Note that the standard library implements higher-order functions as instance methods, not module-level functions. In other words, the Swift methods are accessed via object.method() unlike my functions, which are accessed directly via function().

flatMap for optionals

The Swift standard library provides another mapping function, named flatMap. There are two versions of this function: one that supports mapping optional values and another that supports mapping a sequence of sequences, such as [[Int]] (i.e. an array of array of integers). Here is my implementation of the version for optional values:


This function is like a mixture of map and filter. It creates a sequence of mapped values, but a mapped value is not added to the output sequence when the closure returns nil. In that sense, returning nil is similar to returning false from a closure passed to the filter function.

Tip: flatMap provides a handy way to remove all nil elements from an array of optional values. Here is how you would do this using the standard library’s flatMap method.


flatMap for sequences

The other version of flatMap is for processing a sequence of sequences. It performs something similar to string concatenation, where the mapped elements for each sub-sequence are joined together into one flat sequence.


I’m sure there are more efficient ways to implement this, but I chose to keep this code as straightforward as possible, for the sake of clarity. It, too, is based on reduce, which is just a simple wrapper around a loop.

Parting thought

Higher-order functions that operate on sequences, a seemingly sophisticated concept, can be “reduced” to a simple for-in loop. There is nothing inherently different or special about how they work. What makes them special is how they can elevate your perspective about common programming tasks.

So come on brothers and sisters, let’s get higher.


Posted in Swift | Tagged , | 3 Comments

Creating Tic-tac-toe in Swift: Artificial intelligence

This blog post is the second update about my Tic-tac-toe game, being written in Swift. The source code is available on GitHub:


Over the past week I wrote an intelligent agent which implements the Tic-tac-toe strategy devised by Allen Newell and Herbert Simon in 1972, as explained here. This algorithm is supposed to be a perfect player, meaning it will defeat an imperfect opponent and tie a perfect opponent.

I wrote a method to test that my implementation of the Newell and Simon algorithm is correct when playing against itself. This method is found in GameTests:


As seen above, the Game initializer requires a strategy for each player (X and O). Those arguments must adopt the TicTacToeStrategy protocol:


It might seem odd that the chosen position is passed to a completion handler, instead of simply being returned from the method, but this design will be necessary later to accommodate a human player.

This protocol is adopted by the intelligent agent:


An instance of this class has an ordered sequence of tactics, each of which adopts the NewellAndSimonTactic protocol.


Note that the NewellAndSimonStrategy initializer defines a list of tactics as a default parameter value. This is a useful technique for enabling unit tests to inject mock objects, which is exactly what I did in NewellAndSimonStrategyTests:


A tactic is a means of determining which position to occupy on a game board. For example, CenterTactic is the simplest tactic in the Newell and Simon strategy:


A more complicated and interesting example is WinTactic, which leverages the OutcomeAnalyst that Game uses to detect when a game is over.


The behavior of this tactic is verified by unit test methods defined in WinTacticTests:


In case you’re curious about that board3x3 function, it is part of a simple domain-specific language (DSL) I created for turning a text diagram of a Tic-tac-toe game into the equivalent GameBoard instance. That DSL code can be found in GameBoard+DSL.swift.

My next major milestone is to create an iOS app that consumes the Tic-tac-toe library I’ve written so far. See you next time!

Next article: Creating Tic-tac-toe in Swift: User Interface

Posted in Swift, Tic-tac-toe, Uncategorized | Tagged , | 1 Comment

Creating Tic-tac-toe in Swift: Gameplay and data model

This blog post is an update on my work-in-progress Tic-tac-toe game, being written in Swift. The source code is available on GitHub:


I’ve reached the first major milestone. The program is capable of playing Tic-tac-toe against itself, although there is not yet an intelligent agent deciding where to put each mark on the game board.  Instead, the program has what I call a “scripted strategy” which unit test methods use to advance a game to completion.

Before we get into how that works, here’s a mile-high view of the classes involved so far.


GameBoard is the data model which stores each mark a player puts on the board.

Game orchestrates gameplay between two players.

OutcomeAnalyst is what Game uses to detect when a game is over.

Player represents a contestant, either human or computer.

TicTacToeStrategy describes an object Player uses to choose where to put a mark.

So far the only class which adopts the TicTacToeStrategy protocol is for testing purposes, named ScriptedStrategy.


One interesting thing about this class is that it supports a tiny domain-specific language. As seen in the following example from GameTests (slightly modified to fit this blog’s layout), a ScriptedStrategy is created for each player by parsing a text diagram of a Tic-tac-toe board showing where each Player should put its marks.


Up next I will work on the algorithmic strategy, so that the app’s user will have a challenging opponent to play against. This is a lot of fun!

Next article: Creating Tic-tac-toe in Swift: Artificial Intelligence

Posted in Swift, Tic-tac-toe | Tagged , | 1 Comment