Using Swift’s Unit Test Framework

In an earlier blog post I wrote about my solution to one of the homework assignments for Stanford University’s iOS programming course. My conclusion was that, while the code worked, it seemed a little bit too C-like and not really embracing some of the elegance of the Swift programming language.

My intention is to rewrite the code and see if I can get it looking somewhat more Swifty. But of course in doing that I don’t want to break it – there’s a lot of different cases the CalculatorBrain has to handle. This is a classic scenario that can be solved using automated unit testing.

When you create a new application project in XCode, as well as the main build target you get given a test target with boilerplate code for using XCode’s unit testing framework. It is simple to use – just add new functions to the test class, and use XCTAsserts to ensure the right results.

Continue reading

Programming in Swift – perhaps badly

I have been periodically dabbling in learning Apple’s relatively new Swift programming language. Despite many years of experience in a number of languages including C, C++, C# and Objective-C – yep, that’s a lot of C’s! – my primary reasons for wanting to learn Swift is mental exercise and general interest. My day job these days involves very little programming, but I still consider myself a software developer at heart despite moving heavily into the management side of things. So it is good to keep current and familiar with later technologies. And a further reason for choosing Swift is my interest in developing mobile applications, and Swift looks to be the future of iOS development.

My primary source for learning has been the excellent free Stanford University course CS193P: Developing iOS Apps with Swift, presented by the hugely engaging Paul Hegarty. This course is available for free via iTunesU as a series of videos, slides, and practical exercises. I cannot recommend it enough.

This article is about the homework task of extending the Calculator demo: specifically adding a recursive description method to the CalculatorBrain object to present a readable and mathematically correct text description of the contents of the calculator’s operation stack.

The code snippet below is my implementation. The public getter for the description property contains a loop to solve the formatted output of multiple separate expressions, each comma separated, and is pretty straightforward:

 

    var description: String {
        get {
            var descriptionText = ""
            var (desc,remainingOps) = formatDescription(opStack)
            descriptionText = desc!
            while remainingOps.count > 0 {
                // Comma separate any following complete expressions
                let (desc1,remainingOps1) = formatDescription(remainingOps)
                if desc1 != nil {
                    descriptionText = desc1! + "," + descriptionText
                }
                remainingOps = remainingOps1
            }
            return descriptionText
        }
    }
    

The guts of the solution is in the recursive formatDescription method. It works for the test cases mentioned in the assignment, for example, an operation stack entered in this order:

3 <enter> 5 <enter> 4 + +

gets displayed as:

3+(5+4)

It also handles error conditions such as missing operands being displayed as “?”. So it works.

 
    // Recursive function to format description string
    private func formatDescription(ops: [Op]) -> (desc: String?, remainingOps: [Op]) {
        if !ops.isEmpty {
            var remainingOps = ops
            let op = remainingOps.removeLast()
            switch op {
            case .Operand(let operand):
                return ("\(operand)", remainingOps)
            case .UnaryOperation(let operation,_):
                let (op1Text, remainingOps1) = formatDescription(remainingOps)
                let op1ActualText = op1Text ?? "?"
                let returnText = "\(operation)(\(op1ActualText))"
                return (returnText, remainingOps1)
            case .BinaryOperation(let operation,_):
                let (op1Text, remainingOps1) = formatDescription(remainingOps)
                let (op2Text, remainingOps2) = formatDescription(remainingOps1)
                let op1TextActual = op1Text ?? "?"
                let op2TextActual = op2Text ?? "?"
                let returnText = "\(op2TextActual) \(operation) \(op1TextActual)"
                return (returnText, remainingOps2)
            case .Variable(let variable):
                return (variable, remainingOps)
            case .Constant(let constant):
                return (constant, remainingOps)
            }
        }
        return (nil, ops)
    }

This brings me to the point of this blog post – I think I’m missing something. The formatDescription method does not feel very elegant. Swift has a fantastic type inference engine, and features like optional chaining, which I feel my solution does not take advantage of. You could say it is a little too C or C++ like. All those “let” statements seem overkill.

What do you think? Is there a better more elegant solution?

Using MIT AppInventor in Schools IT

As described in my previous post here, I have been involved in a schools mentoring programme to help expose kids to software development. The New Zealand Techhub Schools IT Challenge started last year in Wellington, and this year has rolled out on a larger scale across the major population centres of the country. The 2015 winners went on to create a shipping mobile phone app with the help of my employer, Datacom. I was fortunate enough to lead that development team, where we took the core ideas of the winning team, and with their help created a brand new application in just a few weeks. See earlier article for links to both the iPhone and Android versions.

Now before you start to get the idea that a big corporate was exploiting the ideas of school children, I should mention that:

  1. the apps are free;
  2. IP remains with the school;
  3. this was an investment by the company in people and resources worth tens of thousands of dollars.

The team got a lot out of it personally, and genuinely got a buzz out of teaching the three girls about software product development and programming. It was satisfying for everybody to take some raw ideas and turn them into shipping code.

A word about the winners. From St Mary’s College for girls in Wellington, for the competition they had to start from nothing, come up with some ideas, and implement what they could using MIT’s AppInventor – more on that later. Other schools in the competition had boys teams, and the stereotypical expectation might be that the boys would win given the much higher proportion of males in the IT workforce. So it was very pleasing to see the girls not only being right up there with the boys teams, but grabbing the prize too.

All of the above is a bit of a long winded introduction to the point of this post. The choice of tools the competitors used was down to the individual schools. The organisers recommended a number of alternatives, but did not dictate any specific platform or technology. One of the options was MIT’s AppInventor. Originally created by Google, the Massachusetts Institute of Technology now maintain and promote it as an educational programming tool to create Android based mobile applications. The school I was mentoring at, St Mary’s College, decided that all teams from that school must use it. For me to be most help, I decided I really ought to learn it too.

I am an experienced developer, and always up for learning new stuff. I have done some iOS programming, but Objective C or Swift and full IDE is a different kettle of fish to a web based graphical programming tool. So I spent some time doing various online tutorials, and this armed me to help answer questions from my teams.

But I would sometimes get questions from the pupils that couldn’t be answered immediately, or required more time and careful explanation than was available in the classroom. They were interesting real-world problems encountered outside the realms of existing online tutorials. I ended up answering these by preparing after class, and then writing something up. Over the next few weeks I intend to publish these notes and targeted AppInventor tutorials in the hope that they will be useful for others.

What is AppInventor?

AppInventor is a web based programming tool for creating Android based applications, and sharing them with others. The tool provides a screen designer that you use to assemble the buttons, text boxes, images, and various user interface components visually. You can customise the behaviour of the controls by writing code blocks. But rather than typing to a particular syntax, code blocks are assembled graphically and connect together using differently shaped connectors to enforce structure. The following example shows a typical code block:

aicodeblock1

 

This is an event handler for a sprite object called Ball1, which gets invoked if the sprite hits any edge of the display area. If it does, it calls a built in method of the sprite that makes it bounce of the edge, and then sets the colour of the ball to a random one chosen from a predefined list. All of these blocks are presented in graphical palettes that the user just drags and drops into their work area. Very slick.

To see your code running, you can launch an Android emulator on your PC or Mac. AppInventor connects to this, loads the code and executes it. Alternatively, you can also connect an Android device via USB or wireless, and the program will be loaded and run from there.

The beauty of AppInventor is that it provides instant gratification. In other words, it is incredibly easy to set something up, write a bit of code, and quickly execute it to see if it does what you expect. As you make changes, they are dynamically uploaded to the emulator, providing a quick feedback loop that is essential to keep young inquiring minds engaged.

I won’t go into more detail on AppInventor here as that can be picked up from existing online resources and my forthcoming notes. Give it a go and play!

Cook Strait

P100

A view across the Cook Strait from Eastbourne near Wellington on the North Island. You can just about make out the snow capped mountains of South Island.

Photo taken on iPhone using Camera+ app. One day I will go back with my DSLR and get a load more photos of this quite stunning area.

Destroying Disk Drives

Photo

I’ve spent a fun hour destroying a bunch of old hard drives that I’ve had hanging around for a few years. While you can get software that wipes disks by repeatedly writing rubbish to it (called disk-shredders), I prefer a hardware solution when throwing away old PC’s. A good old fashioned power drill through the casing and platters is going to do the business. Of course, it may invalidate your warranty!

Why go to such extremes? When you dispose of a PC you never really know where it’s going to end up. It could just go into a landfill, but is more likely to go through some kind of recycling, and there are documented cases of hard disks ending up in the hands of people who try and recover data from them for nefarious purposes. Often such data can aid identity theft, fraud, or open up passwords – how many people store passwords unencrypted in a file on their PC?

So better safe than sorry – take a drill or hammer to your disks before taking them to the tip.