Command Design Pattern in Swift

It is the summer of Swift.

I was perusing some wonderful design patterns from Oktawian Chojnacki, and I decided to play around with the Command pattern. The Command pattern represents commands as objects to go between a Caller, which references the commands, and a Receiver, which is referenced by the commands.

I’m reminded of a game :

RoboRally

Here, each command object operates on a Robo, telling it to make a single move. The commands are collected into a program.

//: Command - Represents commands as objects.

import Cocoa

class Robo : CustomStringConvertible {
    let name : String
    var description: String {
        return name
    }

    init(name: String) {
        self.name = name
    }
}

protocol RoboCommand {
    func execute(robo: Robo)
}

class TurnRight : RoboCommand {
    func execute(robo: Robo) {
        print("\(robo) turns right ➡️")
    }
}

class TurnLeft : RoboCommand {
    func execute(robo: Robo) {
        print("\(robo) turns left ⬅️")
    }
}

class GoForward : RoboCommand {
    func execute(robo: Robo) {
        print("\(robo) goes forward ⬆️")
    }
}

class RoboProgram {
    let robo : Robo
    var commands : [RoboCommand] = []

    init(robo: Robo) {
        self.robo = robo
    }

    init(robo: Robo, commands: [RoboCommand]) {
        self.robo = robo
        self.commands = commands
    }

    func execute() {
        for command in commands {
            command.execute(robo: robo)
        }
    }
}

let robo = Robo(name: "Mikey")
let program = RoboProgram(robo: robo)
program.commands.append(GoForward())
program.commands.append(TurnLeft())
program.commands.append(GoForward())
program.commands.append(GoForward())
program.commands.append(TurnRight())
program.commands.append(GoForward())

program.execute()

The first draft of this code had the Commands store their target Robo in a property. I realized a problem with this in that my program would accept commands for any Robo, when only one Robo belongs to the program. My solution for this was to give control of the command target to the program itself.

Of course, now the commands are little more than glorified functions, which can be stored in arrays in Swift anyway.

Swift Dictionary Reduce

Why is it so hard to find examples of Swift dictionary reduce operations? Examples for arrays abound :

let countme = [1, 2, 3, 4, 5]
let sumall = countme.reduce(0){$0+$1}
// sumall is now 15

See this if you’re looking for a detailed HowTo.

But dictionary is the more advanced problem. How do I reduce when I have keys and values?

The key here is to note that a dictionary yields the contents of its sequence in tuples containing pairs of values. We still have our familiar $0, $1 arguments from reduce as above, where $0 is the partial sum and $1 is the individual element value. But now $0 and $1 are both tuples, and you get to their contents through $0.0, $0.1, $1.0, and $1.1.

let namesNumbers = ["Mike":21, "Bruce":25, "Alice":27]
let (bigname,bignumber) = namesNumbers.reduce(("",0)) 
  {return ($0.0 + $1.0, $0.1 + $1.1)}

This example concatenates the strings and adds the integers, and the two separate data types just happen to use the same symbol for the two operations.

React.JS

React and Angular are popping up a lot in job interviews these days. I decided to try React, since it is rumored to be the simpler of the two. So I created the old Chinese stone game Go in a Codepen. Normally I post code and talk about it in this case, but I think I will just let the Codepen speak for itself. Here, I report my experiences.

There is a lot of learning material out there, but the best resources start out right away with productive examples that get you working quickly. This tutorial video from Traversy Video does a very good job. I used this React demo from Facebook to model my architecture after.

The least trivial part of the game was the capture algorithm. The game engine must figure out if a newly placed stone results in another stone being surrounded. To figure this out, I implemented a recursive breadcrumb algorithm. The method searches recursively in four directions, resulting in a wide descending tree, but marks visited spots on the matrix to prevent infinite recursion. If at any point an empty space (liberty, in game terms) is found, the call stack starts bubbling up with that information. The recursive call will say whether or not a liberty was ever found. If it was, I run a second method to erase all visited points on the matrix, otherwise I run a different method to restore the marked spots back to original.

Here is my reaction (?) to React :

  • JavaScript is fun for web programming in limited amounts, but Object-Oriented frameworks like ES2015, Babel, etc. inevitably make it worse. this.method.bind(this)? Yucko.

  • Hidden inherited methods are traps waiting to happen. My IDE (Codepen) did not alert me to inherited methods, so this may be my own fault for not using a JetBrains tool or some such. Pick unique method names just in case.

  • I don’t really see the payoff. I understand the principle of data flow and limiting state on classes, but a real class-driven language does this in a more flexible way without need of a framework.

I know a little bit of CSS and HTML, so I was able to decorate it a bit, so that it kind of looks like an old wood board.