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!

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

Creating Tic-tac-toe in Swift

Normally I blog about a program I’ve already written. I decided this time to take a different approach, and blog about a Tic-tac-toe program that I’m writing instead. This will give people who are interested in watching a Swift program evolve over time the chance to follow along. As I add new features and refactor the code, I will post about it on this blog.

The repository is on GitHub:

My first committed class is GameBoard. It is the data model that stores the state of a game, namely which positions have been marked with X’s and O’s.

That class’s unit tests are here. The test method naming convention I use is:


You will need the latest Xcode to build this project.


Posted in Swift, Tic-tac-toe | Tagged , | 3 Comments

Compressing a Swift array

Suppose you have an array of values in your Swift app and you need to compress it to a smaller size, with the intention of making it occupy less memory. If the array contains many consecutive repeated values it could be compressed by only including a repeated value once, and tracking the number of consecutive occurrences for that value.

How might that code work? What about the code to decompress an array, how can that be implemented in Swift?

If you are interested in figuring this out yourself, I posted a gist that you can use as a starting point to test your code:

My solution is shown below. It uses some slick Swift goodness, such as a where clause, the flatMap method, and tuple decomposition.


The full source code is available, as a playground, here:

Happy Swifting!

Posted in Swift | Tagged | 1 Comment

I’m back

This blog’s half year of inactivity is over. I had joined Apple as a software engineer, to work on a low-level communications component that runs on all iOS and OS X devices. As an Apple employee I was prohibited from blogging, hence my radio silence. But I decided that working for Apple is not my cup of tea, so I’m back to being a hired gun; a freelance mobile app developer. According to the rules and bylaws of Josh Smith Digital blogging is not only allowed, but encouraged!

Posted in Uncategorized | 6 Comments

Creating ASCII art in functional Swift

This article explores an iOS app, written in a functional Swift style, that converts an image to ASCII art. For example, when given the famous Lenna photograph…

…it creates a string that, when printed, looks something like this…

Zooming into her lovely face reveals that the image is actually text!

The Xcode project is available at

The big picture

Each pixel in an image is mapped to an ASCII value, referred to here as a symbol.

An image’s pixels are first transformed to an intermediary value, as seen below:

Let’s take this step-by-step.

First a pixel’s color is converted to a grayscale color. The grayscale color’s intensity (i.e. brightness) is normalized to a value between 0 and 1, where black is 0 and white is 1.

The next step is, to me, the most interesting part of the algorithm. Each color intensity value is translated to an ASCII symbol. Later we will visit the AsciiPalette class, which supports that.

Lastly, rows of ASCII symbols are joined to form a giant, multi-line string: the ASCII art.

Algorithm implementation

AsciiArtist implements the three steps outlined above; as seen on lines 31 to 33.

An AsciiArtist object relies on Pixel and AsciiPalette, which we’ll look at next.

Transforming pixels to intensities

Pixel represents the color at a specific image coordinate. A color consists of four bytes; one byte per channel (red, green, blue, and alpha). AsciiArtist asks a Pixel to determine its color intensity, which, as previously mentioned, is calculated by normalizing the pixel’s grayscale value to a percentage. Let’s see how that works…

In case you’re wondering about those weight values on lines 47 to 49, they are industry-standard numbers used for grayscale conversion, as explained here.

Transforming intensities to symbols

The symbolFromIntensity function in AsciiArtist transforms a color intensity to an ASCII symbol, by converting a normalized intensity value to an array index. That array is provided by AsciiPalette. The first symbol in the array is used for very dark pixels and the last symbol is for very bright pixels. Here is that AsciiArtist function again, for easy reference:


The question is: which ASCII symbols should be in the array, and in what order?

A poorly designed symbol palette yields improperly shaded ASCII art:

A better symbol palette produces a vastly superior result:

My approach to designing a good symbol palette is to let the computer figure it out. The AsciiPalette class renders each symbol to a separate image, with black text on a white background. It then sorts the symbols by the number of white pixels in their images. The more white pixels in the image, the higher the symbol’s intensity. The blank space character (‘ ‘) has the highest intensity value since it contains only white pixels, and would therefore be the last symbol in the array.

The AsciiPalette designated initializer requires a UIFont argument because the choice of font affects how a character is rendered, impacting the number of white pixels around it.

The code in this article is available at

Posted in Swift | Tagged , | 5 Comments

Zipping two lists in Haskell

Studying a pure functional programming, such as Haskell, can be an eye-opening experience. The standard library in Haskell provides a zip function, which combines the elements of two lists into a single list of tuples. I decided to implement my own version, named zip prime (actually, zip’ since Haskell allows a function name to include the prime (symbol). The simplicity amazes me:

The first line is the function declaration.  It states that zip’ takes two lists of possibly different element types (types a and b) and returns a list of tuples of those element types.

The next line explains what should happen when the second list is empty; return an empty list. Similarly, the line after that explains that an empty list should be returned if the first list is empty.

The fourth and last line of that function covers the case when neither list is empty. It creates a tuple from the first element in each list. That tuple then becomes the list element which precedes the result of zipping together what’s left of the two lists (i.e. zipping their tails).

What could be simpler?! I wish that Swift had this kind of  powerful pattern matching at the function definition level.

Posted in Uncategorized | Tagged ,

Caesar cipher in Swift

I posted a Swift project to GitHub that implements the Caesar cipher, which was the encryption technique used to protect Julius Caesar’s personal correspondence. It’s a straightforward algorithm that maps each letter in the alphabet to another letter.

The code also shows how to break, or “crack”, an enciphered message using basic statistical analysis.



Here are a couple of the unit tests in the CaesarCipherTests class, showing the expected output based on the input string and shift-by argument:

Here is how the encipher method in CaesarCipher works:

The Letters type seen in that code example is a trivial utility struct that simplifies working with an individual letter as its numeric character code. Unfortunately working with individual characters like this in Swift is cumbersome, because of the way Swift supports Unicode text. To treat an individual letter as its character code requires using the UnicodeScalar type, whose value property returns 65 for A, 66 for B, etc.


The decipher method is more complicated than its encipher counterpart. It uses statistical analysis to search for the letter mapping that, when applied to the enciphered text, best matches the expected letter frequencies in a written language’s words (English words, in my case). The statistical tool used to calculate the degree of difference between the observed (O) and expected (E) distributions is known as Pearson’s chi-squared test.

The core idea in the decipher method is to try all 26 possible character mappings and find the one whose relative letter frequencies most closely match the expected letter frequencies. The expected frequencies are calculated on-the-fly, by analyzing a list of English words included in OS X. The LetterFrequency class is responsible for that.

These unit tests from CaesarCipherTests show what to expect from the decipher method, including the fact that it cannot decrypt all messages (especially very short ones).

Here’s how the decipher method in CaesarCipher works…

Happy coding!

Posted in Swift | Tagged , | 2 Comments