Chris' Blog.

My occasional thoughts on iOS development, developers careers, trying to make an income from the App Store, and updates on life in general.

Generating heightmap terrain with Swift

I've had a bit of spare time lately, time off from work for our #3 baby, and I've always been a fan of games with heightmap terrain, so I decided to see how I could generate it with Swift. This post is just a bit of fun, you can skim this one :)


It's called the Diamond-square algorithm and basically it works by repetitively dividing by diamonds then squares. Now this sounds like a good contender for a recursive algorithm, which I initially tried, but that doesn't work because it goes depth-first instead of breadth-first, so a good old for-loop actually works better.

Terrain model

Firstly you need a model object to handle the two-dimensional heightmap. Basically it's a wrapper around an array of floats with some convenience accessors:

class Terrain {
    var array: [Float]
    let size: Int

    /// Creates a new terrain of the given width and height.
    init(size: Int) {
        self.size = size
        array = [Float](count: size*size, repeatedValue: 0)

    /// Sets one point to a given height value.
    func set(x x: Int, y: Int, value: Float) {
        array[y * size + x] = value

    /// Gets the height at a point.
    func get(x x: Int, y: Int) -> Float {
        return array[y * size + x]

    /// Gets a point safely, returning nil if it's clipped outside the area.
    func getClipped(x x: Int, y: Int) -> Float? {
        if x >= 0 && y >= 0 && x < size && y < size {
            return get(x: x, y: y)
        } else {
            return nil

Notice that this uses class semantics, not value semantic (eg it's not a struct). This is because it has to be mutated a lot and isn't a great candidate for functional programming as far as I can see .

Diamond-square steps

Next we need to implement the diamond and square steps. I'm not going to explain how these work (I'll probably confuse you more!) - so read the wiki entry if you're unfamiliar.

Notice that these steps are implemented as an extension. This is to keep the code separate from the code above, as this generation code is really auxiliary (eg you might simply load the map from disk and not need to generate it). Nice design principle to keep in mind: If it's not core functionality, consider putting it in an extension.

/// Returns in the range -1..1
func frand() -> Float {
    return Float(drand48() * 2 - 1)

extension Terrain {

    /// Sets the midpoint of the square to be the average of the four corner points plus a random value.
    /// x,y are the top left values.
    func diamond(x x: Int, y: Int, size: Int, randomScale: Float) {
        let tl = get(x: x,        y: y)
        let tr = get(x: x + size, y: y)
        let bl = get(x: x,        y: y + size)
        let br = get(x: x + size, y: y + size)
        let avg = (tl + tr + bl + br) / 4
        set(x: x + size/2, y: y + size/2, value: avg + frand() * randomScale)

    /// Sets the midpoints of the sides of the square to be the average of the 3 or
    /// 4 horiz/vert points plus a random value.
    func square(x x: Int, y: Int, size: Int, randomScale: Float) {
        // Get all the inputs.
        let half = size/2
        let tl = get(x: x,        y: y)
        let tr = get(x: x + size, y: y)
        let bl = get(x: x,        y: y + size)
        let br = get(x: x + size, y: y + size)
        let m  = get(x: x + half, y: y + half)
        let above = getClipped(x: x + half,        y: y - half)
        let below = getClipped(x: x + half,        y: y + size + half)
        let left  = getClipped(x: x - half,        y: y + half)
        let right = getClipped(x: x + size + half, y: y + half)

        // Set the sides.
        set(x: x + half, y: y,        value: average(tl, tr, m, above) + frand() * randomScale) // Top
        set(x: x + half, y: y + size, value: average(bl, br, m, below) + frand() * randomScale) // Bottom
        set(x: x,        y: y + half, value: average(tl, bl, m, left)  + frand() * randomScale) // Left
        set(x: x + size, y: y + half, value: average(tr, br, m, right) + frand() * randomScale) // Right

    /// Average of the 3 or 4 inputs.
    private func average(a: Float, _ b: Float, _ c: Float, _ d: Float?) -> Float {
        if let d = d {
            return (a+b+c+d) / 4
        } else {
            return (a+b+c) / 3


Next is the actual generator that iterates through the diamond-square steps to create a new map. I initially wrote this to use recursion but it ended up being depth-first not breadth-first and the generated terrain was terrible. I'm sure a haskell guru could make this beautiful.

extension Terrain {

    /// The height/width is 2^detail+1.
    /// Eg detail=8 -> size=257 -> ~1/4 megabyte
    /// Roughness 1 = rough, 0 = flat. 0.6 looks good.
    static func generatedTerrainWithDetail(detail: Double, roughness: Float) -> Terrain {
        let size = Int(round(pow(2, detail) + 1)) // Will be the number of array elements in each dimension (odd number).
        let max = size - 1 // The maximum index.
        let map = Terrain(size: size)

        // Initial corner values.
        map.set(x: 0,   y: 0,   value: frand())
        map.set(x: max, y: 0,   value: frand())
        map.set(x: 0,   y: max, value: frand())
        map.set(x: max, y: max, value: frand())

        // Fill it in.
        for var subSize = max, randomScale: Float = 1; subSize > 1; subSize /= 2, randomScale *= roughness {
            for var y = 0; y < max; y += subSize {
                for var x = 0; x < max; x += subSize {
                    map.diamond(x: x, y: y, size: subSize, randomScale: randomScale)
            for var y = 0; y < max; y += subSize {
                for var x = 0; x < max; x += subSize {
                    map.square(x: x, y: y, size: subSize, randomScale: randomScale)

        return map


In a future post, I might write about how to render this using SceneKit.

Thanks for reading!

Swift Education Screencasts

Recently I've been recording a series of free screencasts that follow the Swift Education curriculum created by Yong Bakos and featured by Apple.

So, next time anyone asks "how do you make apps?", point them in the direction of these videos. Hope they're helpful!

Word Collage

Swift Education link


Swift Education link

Swift Image Cache

A lot of people are scratching their heads now we're all using Swift, wondering 'which image caching library shall I use?'. Hopefully I can throw an option in the ring.

If your image-loading requirements are fairly basic: you want reasonable speed, but you don't want to worry about the potential delays involved in saving/loading to disk, you may want to consider simply using NSCache - Foundation's built-in caching class.

One thing this solution brings to the table is that it is easy to determine if a given image is already cached or not. This is often very useful eg when scrolling table views: if an image is cached, you simply set the image with no animations. However if the image isn't cached, you must display a placeholder, and crossfade the image once loaded - two distinct code paths. One of my biggest gripes with SDWebImage, for instance, is that this is difficult (although not impossible). I feel this use-case should be emphasised by the image cache.

The code

class MyImageCache {

    static let sharedCache: NSCache = {
        let cache = NSCache() = "MyImageCache"
        cache.countLimit = 20 // Max 20 images in memory.
        cache.totalCostLimit = 10*1024*1024 // Max 10MB used.
        return cache


extension NSURL {

    typealias ImageCacheCompletion = UIImage -> Void

    /// Retrieves a pre-cached image, or nil if it isn't cached.
    /// You should call this before calling fetchImage.
    var cachedImage: UIImage? {
        return MyImageCache.sharedCache.objectForKey(
            absoluteString) as? UIImage

    /// Fetches the image from the network.
    /// Stores it in the cache if successful.
    /// Only calls completion on successful image download.
    /// Completion is called on the main thread.
    func fetchImage(completion: ImageCacheCompletion) {
        let task = NSURLSession.sharedSession().dataTaskWithURL(self) {
            data, response, error in
            if error == nil {
                if let  data = data,
                        image = UIImage(data: data) {
                        forKey: self.absoluteString, 
                        cost: data.length)
                    dispatch_async(dispatch_get_main_queue()) {


How to use it

Say you've got a UITableView with cells that need images. Firstly, i'd have two UIImageViews, one under the other. The underneath view would always contain a placeholder image, eg a watermark of a camera in dark grey on a light grey background. And the upper image would contain the actual image.

In your cellForRowAtIndexPath method, you firstly will try to grab the image from the cache. If it is available, you set the upper image immediately, and set its alpha to 1. If it is not available, you set the upper image's alpha to 0, load the image, then once loaded you set the image and animate the alpha to 1. It'll look like the below:

class MyCell: UITableViewCell {
    var placeholderImageView: UIImageView!
    var myImageView: UIImageView!
    var imageUrl: NSURL!
    // ...

struct MyModel {
    let text: String
    let imageUrl: NSURL
    // ...

class MyViewController: UITableViewController {
    var models: [MyModel]!

    override func tableView(tableView: UITableView,
            cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let data = models[indexPath.row]
        let cell = tableView.dequeueReusableCellWithIdentifier("cell",
            forIndexPath: indexPath) as! MyCell
        cell.textLabel?.text = data.text

        // Image loading.
        cell.imageUrl = data.imageUrl // For recycled cells' late image loads.
        if let image = data.imageUrl.cachedImage {
            // Cached: set immediately.
            cell.myImageView.image = image
            cell.myImageView.alpha = 1
        } else {
            // Not cached, so load then fade it in.
            cell.myImageView.alpha = 0
            data.imageUrl.fetchImage { image in
                // Check the cell hasn't recycled while loading.
                if cell.imageUrl == data.imageUrl {
                    cell.myImageView.image = image
                    UIView.animateWithDuration(0.3) {
                        cell.myImageView.alpha = 1

        return cell


To be honest, it may make more sense to make a custom view that contains these two image views, and let it handle these responsibilities. I'll leave that as an exercise to the reader.

Cell recycling

Any discussion about async image loading isn't complete without talking about cell recycling in table views. A common race condition occurs when scrolling quickly: by the time an image is loaded, that cell has been recycled and it'll be wrong to set the image on that cell.

To deal with this, I recommend adding an extension on the UIImageView class which stores an image URL as an associated object. Read here for how to do this. Alternatively you can add an imageUrl variable to custom cell subclasses as I did in the above example.

When it comes time to configure a cell, do the following:

  • Set the text label as normal
  • Set the image view's URL immediately
  • If the image is cached, set the imageView.image immediately
  • If it isn't cached, load the image:
    • When the image returns, set the imageView.image only if the imageView's URL == the model object's image URL

One less Cocoapod

I'm a big proponent of cutting down the number of third-party dependencies your app has. I have no ideology here, simply pragmatism: I've simply been burned way too many times by poorly-engineered cocoapods. I'm much more of a fan of blogging a suggestion for a simple solution, and letting you copy and paste it and customise it further if you need it.

In fact, if you combine this image cache with my wrapper for NSURLSession, you can obviate the requirement for the two biggest reasons I have for using Cocoapods at all. In fact, in my current project, by doing this, I do not need to use cocoapods/carthage, and life is good. You may wish to consider the same.

Other options

If you're the next Flickr or Instagram and this doesn't look suitable for you, there's always Haneke or good old SDWebImage.

Thanks for reading!

You can see older posts in the right panel, under 'archive'.


Generating heightmap terrain with Swift 8 Nov 2015

Swift Education Screencasts 27 Oct 2015

Swift Image Cache 24 Sep 2015

Don't be slack 13 Sep 2015

Swift KVO alternative 23 Jul 2015

Swift Keychain wrapper 21 Jun 2015

Swift NSURLSession wrapper 12 Jun 2015

iOS8 View Controller transitioning bug 17 Apr 2015

IB Designable 18 Mar 2015

iOS App Architecture 2 Mar 2015

Video Course Launch 14 Feb 2015

Video Course Pre-launch 8 Feb 2015

Blogging Platforms 13 Jan 2015

Mobile in 2014 - Year in Review 11 Jan 2015

Secret Keys talk 16 Nov 2014

Dimmi 11 Nov 2014

Project setup in Xcode6 22 Oct 2014

Uploading to an S3 bucket from iOS 15 Oct 2014

iOS8 App Testing Roundup 28 Sep 2014

Storing obfuscated secret keys in your iOS app 16 Sep 2014

Getting Core Location / CLLocationManager to work on iOS8 14 Sep 2014

Accessing the response body in failure blocks with AFNetworking 2 10 Sep 2014

How to allow your UITextFields to scroll out of the way of the keyboard 8 Sep 2014

How to subclass UIButton in iOS7 and make a UIButtonTypeSystem 4 Sep 2014

New season 1 Aug 2014

House finished 17 Jun 2014

WebP decoding on iOS 9 Feb 2014

Moving on again 22 Jan 2014

Lossy images for retina iPads - JPEG vs WebP 30 Nov 2013

Career options I wish I knew about when I was younger 20 Oct 2013

Positivity and your friends 7 Oct 2013

Tactility 26 Jul 2013

WWDC-induced narcolepsy 15 Jul 2013

Back on rails 31 May 2013

Full circle 6 May 2013

Programmatic UI on iOS 3 May 2013

Screencasts and positivity 8 Apr 2013

Year of positivity 14 Mar 2013

iOS Dev State of the Union 6 Feb 2013

Adventures with IAPs 3 Feb 2013

No longer a Googler 23 Dec 2012

Localising iPhone apps with Microsoft Translator 8 Dec 2012

Fight back (app biz update 13) 12 Nov 2012

Sent to the backburner (app biz update 12) 25 Oct 2012

Lisi Schappi 7 Oct 2012

Today's happy plateau (app biz update 11) 26 Aug 2012

First week's sales of Today (app biz update 10) 19 Aug 2012

Today launch! And a difficult decision made... (app biz update 9) 15 Aug 2012

Approved! (app biz update 8) 5 Aug 2012

Creating a graph in Objective-C on the iPhone 3 Aug 2012

Hurry up and wait (app biz update 7) 30 Jul 2012

Today app marketing site 27 Jul 2012

Today app submitted 25 Jul 2012

UIAlertView input wrapper 24 Jul 2012

Mentoring 23 Jul 2012

This is too hard! (app biz update 6) 20 Jul 2012

Perspectives (app biz update 5) 9 Jul 2012

4th starting-my-own-biz update 1 Jul 2012

ScrumFox landing page 28 Jun 2012

Server Scope landing page 27 Jun 2012

Telstra Calls and Data Usage 26 Jun 2012

Service History + Dropbox 26 Jun 2012

Impromptu Presenter 26 Jun 2012

Fertility Tracker 26 Jun 2012

Baby Allergy Tracker 26 Jun 2012

Starting my own business, update 3 22 Jun 2012

Starting my own business, update 2 17 Jun 2012

Starting my own business - First update 10 Jun 2012

I must be crazy 6 Jun 2012

Finding your location on an iPhone 7 May 2012

A generous career 4 May 2012

Skeleton Key Cocoaheads presentation 3 May 2012

CHBgDropboxSync - Dropbox auto-sync for your iOS apps 1 May 2012

That book about that Steve Jobs guy 30 Apr 2012

Another app marketing idea 23 Apr 2012

Sweet grouped tables on the iPhone 17 Apr 2012

Skeleton Key App 11 Apr 2012

Another app marketing idea... 5 Apr 2012

Quickly check for any missing retina graphics in your project 3 Apr 2012

Skeleton Key Password Manager with Dropbox 2 Apr 2012

RC Boat motor finally mounted 2 Apr 2012

Promoting apps presentation slides 1 Apr 2012

How i just wasted a month on my latest app, and how you don't need to 26 Mar 2012

The Finishing Line 20 Mar 2012

Using Launchd to run a script every 5 mins on a Mac 20 Feb 2012

Generating AES256 keys from a password/passphrase in ObjC 20 Feb 2012

Indie iPhone app marketing, part 2 19 Feb 2012

My App Manifesto: Syncing + Dropbox + YAML = Awesome 15 Feb 2012

Indie iPhone App Marketing part 1 7 Feb 2012

Perspectives 2 Feb 2012

Accountability and Free Will 1 Feb 2012

Badassery 31 Jan 2012

Sacrifice 30 Jan 2012

Lead Yourself First 29 Jan 2012

How to ping a server in Objective-C / iPhone 26 Jan 2012

iOS Automated Builds with Xcode4 16 Jan 2012

Xcode 4 - Command line builds of iPhone apps 15 Jan 2012

Guest post by Jason McDougall 13 Jan 2012

Scouts, Games and Motivation 10 Jan 2012

2011 Re-cap 8 Jan 2012

Ruby script to increment a build number 4 Jan 2012

Turning 30? All ideas, no execution? 18 Dec 2011

CHDropboxSync - simply sync your iOS app's documents to Dropbox 14 Dec 2011

Deep-enumerating a directory on the iphone, getting file attributes as you go 10 Dec 2011

Getting a date without the time component in objective-c 6 Dec 2011

Memory management in Objective-C 4 Dec 2011

Starting small 29 Nov 2011

Dictionary Types Helper 29 Nov 2011

Observer Pattern in Objective-C 16 Nov 2011

Why you should give presentations 13 Nov 2011

How to get a programming or design job in Sydney 9 Nov 2011

Custom nav bar / toolbar backgrounds in iOS5 8 Nov 2011

Stuck 27 Oct 2011

Dead easy singletons in Obj-C 19 Oct 2011

JSON vs OCON (Objective-C Object Notation) 18 Oct 2011

In defence of Objective-C 16 Oct 2011

Update the MessagePack objective-c library to support packing 12 Oct 2011

Icons 11 Oct 2011

How to host a site on Amazon AWS S3, step-by-step 7 Oct 2011

Drawing a textured pattern over the default UINavigationBar 6 Oct 2011

Markdown Presentations 1 Oct 2011

More MegaComet testing: Ruling out keepalives 15 Sep 2011

MegaComet test #4 - This time with more kernel 14 Sep 2011

Building People 10 Sep 2011

Half way there: Getting MegaComet to 523,000 concurrent HTTP connections 5 Sep 2011

Making a progress bar in your iPhone UINavigationBar 22 Aug 2011

Hacker News Reader 20 Aug 2011

How to programmatically resize elements for landscape vs portrait in your iphone interface 16 Aug 2011

MegaComet testing part 2 3 Aug 2011

Australian Baby Colours 28 Jul 2011

Boat prop shaft 25 Jul 2011

Megacomet with 1 million queued messages 24 Jul 2011

Installed the strut and rudder 18 Jul 2011

Painted the inside of the boat 17 Jul 2011

Fuzzy iphone graphics when using an UIImageView set to UIViewContentModeCenter 13 Jul 2011

My 3 Data and Calls Usage 11 Jul 2011

Reading a line from the console in node.js 10 Jul 2011

Trim whitespaces on all text fields in a view controller 9 Jul 2011

Final finish 9 Jul 2011

MessagePack parser for Objective-C / iPhone 30 Jun 2011

Lacquering the starboard side 25 Jun 2011

What do do with EXC_ARM_DA_ALIGN on an iPhone app 23 Jun 2011

Lacquering the hull 23 Jun 2011

Staining the boat 22 Jun 2011

NSMutableSet with weak references in objective-c 20 Jun 2011

Iphone gesture recogniser that works for baby games 20 Jun 2011

Image manipulation pixel by pixel in objective C for the iphone 19 Jun 2011

Baby Allergy Tracker 12 Jun 2011

Power sanding the deck 10 Jun 2011

Planing the edge of the deck 2 Jun 2011

Figured out the deck 2 Jun 2011

Boat bulkheads 2 Jun 2011

Simulating iOS memory warnings 31 May 2011

Putting a UIButton in a UIToolbar 29 May 2011

How to allow closing a UIActionSheet by tapping outside it 29 May 2011

Finding the currently visible view in a UITabBarController 24 May 2011

Random Chef 17 May 2011

Centered UIButton in a navigation bar on the iphone 16 May 2011

Little Orchard 13 May 2011

Boat update 13 May 2011

How to get the current time in all time zones for the iphone / obj-c 12 May 2011

Design portfolio 10 May 2011

Tricks with grand central dispatch, such as objective-c's equivalent to setTimeout 9 May 2011

How to make an iphone view controller detect left or right swipes 5 May 2011

Centered section headers on a UITableView 5 May 2011

Christmas in may 4 May 2011

Finished trimming the boat (its floatable now!) and got some parts 29 Apr 2011

How to make a multiline label with dynamic text on the iphone and get the correct height 27 Apr 2011

Forcing an image size on the image in a table view cell on an iphone 20 Apr 2011

Git on the Mac 19 Apr 2011

Build a url query string in obj-c from a dictionary of params like jquery does 12 Apr 2011

Rendering a radial gradient on the iphone / objective-c 11 Apr 2011

Skinning the port side of the boat 8 Apr 2011

Skinning the side of the boat 5 Apr 2011

Sending a UDP broadcast packet in C / Objective-C 5 Apr 2011

How to talk to a unix socket / named pipe with python 4 Apr 2011

Skinning the bottom of the boat 31 Mar 2011

Service discovery using node.js and ssdp / universal plug n play 30 Mar 2011

Extremely simple python threading 29 Mar 2011

New rescue boat 26 Mar 2011

HttpContext vs HttpContextBase vs HttpContextWrapper 5 Nov 2010

Simple C# Wiki engine 30 Sep 2010

Simple way to throttle parts of your Asp.Net web app 29 Sep 2010

How to implement DES and Triple DES from scratch 4 Aug 2010

How to use sessions with Struts 2 30 Jul 2010

How to use Cookies in Struts 2 with ServletRequest and ServletResponse 30 Jul 2010

Using Quartz Scheduler in a Java web app (servlet) 27 Jul 2010

Javascript date picker that Doesn't Suck!(tm) 27 Jul 2010

Using Oracle XE with Hibernate 20 Jul 2010

A simple implementation of AES in Ruby from scratch 29 Jun 2010

Asp.Net Forms authentication to your own database 28 May 2010

AS2805 (like ISO8583) financial message parser in C# 7 May 2010

Ruby hex dumper 4 May 2010

Using Spring to manage Hibernate sessions in Struts2 (and other web frameworks) 13 Jan 2010

Emails in C#: Delivery and Read receipts / Attachments 12 Jan 2010

Using Java libraries in a C# app with IKVM 16 Dec 2009

Learning Java tutorial 27 Nov 2009

Using generic database providers with C# 17 Nov 2009

Scheduled task executable batch babysitter 29 Oct 2009

Working with query strings in Javascript using Prototype 30 Sep 2009

Still fighting with String.Format? 9 Sep 2009

How I'd build the next Google 24 Aug 2009

Getting IIS and Tomcat to play nicely with isapi_redirect 24 Aug 2009

Using the new ODP.Net to access Oracle from C# with simple deployment 11 Aug 2009

C# Cryptography - Encrypting a bunch of bytes 14 Jul 2009

Sorting enormous files using a C# external merge sort 10 Jul 2009

Reconciling/comparing huge data sets with C# 9 Jul 2009

Some keyboard-friendly DHTML tricks 10 Jun 2009

How to figure out what/who is connected to your SQL server 18 Mar 2009

Adding a column to a massive Sql server table 16 Mar 2009

Multithreading using Delegates in C# 10 Mar 2009

Using C# locks and threads to rip through a to-do list 6 Feb 2009

Using threads and lock in C# 3 Feb 2009

Compressing using the 7Zip LZMA algorithm in C# beats GZipStream 14 Jan 2009

MS Sql Server 2005 locking 17 Dec 2008

Simple Comet demo for Ruby on Rails 19 Nov 2008

Geocoding part 2 - Plotting postcodes onto a map of Australia with C# 24 Oct 2008

Using evolutionary algorithms to make a walkthrough for the light-bot game with C# 20 Oct 2008

How to tell when memory leaks are about to kill your Asp.Net application 16 Oct 2008

C# version of isxdigit - is a character a hex digit? 15 Sep 2008

Geocoding part 1 - Getting the longitude and latitude of all australian postcodes from google maps 26 Aug 2008

Converting HSV to RGB colour using C# 14 Aug 2008

Opening a TCP connection in C# with a custom timeout 11 Aug 2008

Oracle Explorer - a very simple C# open source Toad alternative 31 Jul 2008

Linking DigitalMars' D with a C library (Mongrel's HTTP parser) 23 Jun 2008

Connecting to Oracle from C# / Winforms / without tnsnames.ora 16 Jun 2008

A simple server: DigitalMars' D + Libev 6 Jun 2008

Travelling from Rails 1 to Rails 2 9 Apr 2008

Online Rostering System 9 Apr 2008

DanceInforma 9 Apr 2008

Using RSS or Atom to keep an eye on your company's heartbeat 10 Nov 2007

Easy Integrated Active Directory Security in ASP.Net 24 Oct 2007