Swift Structs and accessing properties by name

Brent Simmons posted a blog article today about a feature he was missing from Swift that was readily available in Objective-C – the ability to access properties of an object indirectly using a string.

Brent’s goal is to be able to write some generic code that compares various different properties. Here’s how he puts it:1

For every merge-able property there are really two properties, and there’s a simple naming convention.

For example, a note’s archived flag has two properties: archived and archivedModificationDate.

Merging works like this pseudo-code:

if existingObject.archivedModificationDate < serverObject.archivedModificationDate {
existingObject.archived = serverObject.archived
existingObject.archivedModificationDate = serverObject.archivedModificationDate
}

But the code doesn’t actually look like that. Instead of duplicating the above for each property, there’s a single method that takes server object, existing object, and property name as parameters. Then it uses valueForKey: on both server object and existing object. (It gets the key for the date value by adding “ModificationDate” to the property name.)

This turns merging a given property into a one-liner:

mergeProperty(existingObject, serverObject, “archived”)

He asks if there’s a way to do this right now. The answer is almost, with some shortcomings (most of which will hopefully get resolved before the end of the beta).

Firstly, here’s an example version of a struct with some properties:

(I’m using Int as a stand-in for a date/time object, for simplicity)

struct Properties {
    // someday soon these can be private
    var _name: String, _nameModificationDate: Int
    var _shape: String, _shapeModificationDate: Int

    init(name: String, nameModificationDate: Int,
         shape: String, shapeModificationDate: Int) {
            self._name = name
            self._nameModificationDate = nameModificationDate
            self._shape = shape
            self._shapeModificationDate = shapeModificationDate
    }

    func name()->String { return _name }
    func nameModificationDate()->Int { return _nameModificationDate }

    func shape()->String { return _shape }
    func shapeModificationDate()->Int { return _shapeModificationDate }
}

Note that the “getter” methods for name and shape are methods, not var properties with a { get }. This will be important later.

This struct is both immutable in the sense that there are no setter methods, and also can be immutable because it’s a struct you can declare with let instead of var. There’s an important distinction here – classes can be immutable too, in the former sense. A pattern in the Swift standard library is to declare an immutable version of a protocol that only has read methods (such as Collection, that declares an rvalue version of subscript), and then an inherited version that is mutable and has write methods (such as MutableCollection, that declares an lvalue version of subscript).

Of course, right now there’s no private variables in Swift, so internal variables are still writeable, but Apple have made it pretty clear this is coming in a later beta.

Having declared our struct, we create a dictionary that can be used to access the getter methods:

let propertyDict = [
    "Name":  (Properties.name, Properties.nameModificationDate),
    "Shape": (Properties.shape, Properties.shapeModificationDate),
]

This dictionary maps a string name onto a tuple containing two member function references,2 one for the property and one for its associated modification date. They have a type of Properties->()->String (or ->Int ). You use them first by applying an instance of the object, which returns a new function bound to that instance, and then calling the function.

Here is why the accessors had to be methods. To my knowledge, you can’t do the same thing with var propertyName { get } properties, for the simple reason they don’t need () to invoke, so you can’t leave it off to get the method reference. Maybe under the hood there’s a secret get_propertyName() function you could use, but I can’t find it.

To demonstrate these in use, here’s the implementation of the mergeProperty function:

func mergeProperty(existingObject: Properties,
    serverObject: Properties,
    propertyName: String) 
    -> (String, Int) {

        // fetch the property-accessing member function references
        // associated with propertyName
        if let (property, propModDate) = propertyDict[propertyName] {

            // now get the modification date for this property
            // for both the existing and server versions
            let existingModDate = propModDate(existingObject)()
            let serverModDate = propModDate(serverObject)()

            // do your date comparison to pick the winner
            if existingModDate >= serverModDate {
                return (property(existingObject)(), existingModDate)
            }
            else {
                return (property(serverObject)(), serverModDate)
            }
        }
        else {
          // throw an exception! (only kidding, in practice mergeProperty's 
          // return type should probably be optional and return nil to 
          // account for this possibility
          return ("",0)
        }
}

And here is the mergeProperty function in use:

let existingObj = Properties(name: "Fred", nameModificationDate: 10,
    shape: "Square", shapeModificationDate: 20)

let serverObj = Properties(name: "Bob", nameModificationDate: 12,
    shape: "Circle", shapeModificationDate: 18)


let (mergedName, _) = mergeProperty(existingObj, serverObj, "Name")
let (mergedShape, _) = mergeProperty(existingObj, serverObj, "Shape")

// mergedName = Bob, and mergedShape = Square

There are a lot of likely objections to the above code, some of which can be addressed by more code, some by possibly-upcoming Swift enhancements, and some that are just fundamental to Swift.

The hardcoding of the entries in propertyDict. This is the inevitable result of there being no official reflection in Swift. Yet. There’s clearly the beginnings of reflection with the getMirror() method and AnyClass type. I’d be surprised if Swift made it all the way through beta without it being added. Once there’s reflection, you could build up propertyDict at runtime (and also hopefully compile time if you prefer) based on a list of property names and a naming convention.

Jason Peebles tweeted an alternative, that involves access to the raw member variables using the nascent reflection capabilities. This is very interesting, and kind of like solving this from the other end. My concerns with this approach is it feels better to me to use methods, though maybe that’s my own prejudice. Also, that current reflection API is possibly temporary and only there to facilitate the playground and debugger. Eventually when full reflection is implemented, hopefully both methods and member variables will be exposed (maybe they are already with a bit more playground spelunking).

It only supports strings. In real-world use, you would wrap up propertyDict and mergeProperty together into a class (along with the reflection that took the metaclass and a list of property names), which you could then make generic to operate on Int or String accessors depending on need.

Use of methods instead of properties. I don’t know how to fix this right now. Leave a comment if you do! But for the most part, anything you can do with properties you can also do with getting and setting methods, so it’s not a deal-breaker.3 This is the biggest sticking point though.

It’s not how it works in Objective-C. More of a philosophical difference, this one. But you could probably reproduce nearly all the behaviour of valueForKey using the above technique. The solution using generics is still going to leave you fighting the type system a bit more than you might in Objective-C, and while using Any instead might get you closer, I usually find myself fighting even harder with Any than I did with types.

An implementation that is true to the valueForKey behaviour, by which any property can be fetched with a single method call, seems by definition to require a return of an Any variable which gives up much of the type safety Swift is forcing you towards. Maybe whatever reflection solution eventually emerges will show a pleasing middle-ground.

Anyway, hopefully this solves at least part of Brent’s problem. Maybe some day some of this code will make it into Vesper, which would be very exciting as I’m a big fan of the app.


  1. Sorry about butchering the code part. My blog engine and I are not getting along. 
  2. I made that term for them up, by the way. It’s not like an official name for them or anything. It’s what they’re called in C++, which Swift seems to model in this respect. 
  3. At least until Apple implements KVO in Swift only for properties. Then this technique is screwed. 

Always write a generalized version of your algorithm

Suppose you want to find the minimum value in an array. Well, the Swift standard library has you covered:

let a = [6, 2, 4, 7, 8, 10]
minElement(a)  // returns 2

Ok that’s cool. But suppose you have an array of strings of integers and you want the minimum numeric value.

Well, I guess you could map them to Int and then use the same function:

let a = ["6", "2", "4", "7", "8", "10"]
minElement( a.map { $0.toInt() })

Nope, compiler error. String.toInt returns an Int?, because maybe the string isn’t a number.

Fair enough. I happen to know with my intimate knowledge of the problem domain that we can just ignore non-numeric values. So maybe filter those out?

minElement( a.map { $0.toInt() }.filter { $0 != nil } )  // hmmm

Nope, more compiler errors, because now we have only non-nil values, but they’re still optionals and an Int? doesn’t conform to Comparable. So maybe another map to force-unwrap the results (force unwrap is OK because the filter will guarantee no non-nil elements):1

minElement( a.map{ $0.toInt() }.filter { $0 != nil }.map { $0! } )  // yuck

Ok that compiles now and does return the minimum numeric value. But what if we wanted the result to still be a string?

"\(minElement( a.map{ $0.toInt() }.filter { $0 != nil }.map { $0! } ))" // bleurgh

That’s pretty horrible, and at this point I’m thinking of registering GiveUpAndUseAforLoop.com,2 and Marco Arment is yelling at you kids with your new language to get off his lawn.

Really, what we need is for minElement to take a predicate instead of only using the default <. It doesn't (mutter, grumble) but if it did, we could write this:

minElement(a) {
    switch ($0.toInt(), $1.toInt()) {
    case (_, nil): return true
    case (nil, _): return false
    case (let i, let j): return i < j
    }
}

Ahh. Faith in the functional programming style restored.3 This takes each element, checks if the toInt() of either is nil using pattern matching, always preferring the non-nil version, and if neither are, compares them. Since all it's doing is comparing the converted value, not returning one, the minimum returned is a string.4

There's nothing stopping you from implementing your own overload of Apple's minElement that takes a predicate:5

func minElement
  <E, R: Sequence
  where E == R.GeneratorType.Element>
  (range: R, pred: (E,E)->Bool) -> E {

    var gen = range.generate()
    var min_so_far = gen.next()!

    while let next = gen.next() {
        if(pred(next,min_so_far)) {
            min_so_far = next
        }
    }

    return min_so_far
}

This version copies the Swift library version's questionable practice of exploding in flames if you pass it an empty sequence – the (better?) alternative being make the return value optional to force the caller to acknowledge this possibility.

The moral here is that if you ever write a high-order function, write it as generally as possible. It's only a few extra lines to declare the common case using the general case:6

func minElement
  <E: Comparable, R: Sequence
  where E == R.GeneratorType.Element>
  (range: R) -> E {
    return myMinElement(range, <)
}

Apple does this for most functions (such as sort), just not minElement. But then it is only beta 3, hang in there.


  1. “I thought it was guaranteed not to be nil at this point” is what you could write to the log file in the outer exception handler you can’t have. 
  2. Just kidding, I didn’t think about it, I registered it straight away. 
  3. This code would be even neater if the Swift switch statement would implicitly return the values of single-line cases, i.e. if all the returns in that closure were removed, the switch would evaluate to the value of the selected case statement, and the closure would return it. They closed my radar as a dupe of 16169366 (don't file another duplicate though). 
  4. It's still not perfect – if none of the elements are numeric, it'll return the first one. Also, it'll convert each element twice. Hold that thought for a later post though. 
  5. Actually, there might be some compiler bugs stopping you, but I'll leave you to discover those on your own. 
  6. If the language would let you, you could even default the last parameter to <, but it won't, so you can't. More dynamic default arguments (including ones derived from other arguments to the same function) could be pretty useful in cutting down the amount of code you need to write for these general- and special-case versions. 

Swift’s Lazy Collections and Sequences

Warning: this article is out of date as of Swift 1.0 beta 4. Read this updated version instead.

The Swift non-member function map acts much like the Array.map member function, except you can pass in any kind of sequence or collection (click here for an article on how to write an algorithm like this).

But if you look at what map returns, it isn’t an array of results. It’s an object (a MapColectionView or a MapSequenceView).

That’s because map evaluates its results lazily. When you call map, no mapping takes place. Instead, the input and mapping function are stored for later, and values are only mapped as and when they are needed.

To see this happening, run the following code:

let r = 1...3
let mapped = map(r) {
    (i: Int) -> Int in
    println("mapping (i)")
    return i*2
}

println("crickets...")

for i in mapped {
    println("mapped (i)")
}

println("tumbleweed...")

println("index 2 = (mapped[2])")

// prints out
crickets...
mapping 1
mapped 2
mapping 2
mapped 4
mapping 3
mapped 6
tumbleweed...
mapping 2
index 2 = 4

The returned object from map mimics the properties from the object passed in. If you pass in a sequence, then you get back a sequence. If the collection you passed in only supported a bidirectional index (such as a Dictionary or a String, which can’t be indexed randomly), then you won’t be able to subscript arbitrarily into the mapped collection, you’ll have to walk through it.

map is not the only lazy function. filter and reverse also return these “view” classes. Combining these different lazily evaluated classes means you can build up quite complicated expressions without sacrificing efficiency.

Want to search backwards through an array or string? find(reverse(myarray), value) won't actually reverse the array to search through it, it just iterates over the ReverseView class, which serves up the array in reverse order.

Want the first 3 odd numbers that are a minimum of two arrays at each position? first_n(filter(map(Zip2(a1, a2), min) {$0%2 == 1}, 3) wont do any more zipping or minning or modding than necessary.123

There are also several lazily generated sequences you can also use:

enumerate numbers each item in a collection — it returns an EnumerateGenerator, that serves up those numbered elements on demand. This is useful in a for (count, val) in enumerate(seq) loop where you want to know both the value and how many values so far.

PermutationGenerator is initialized with a collection and a collection of indices into that collection, and serves up each element at each index in that order (thus allowing you to lazily reorder any collection – for example, PermutationGenerator(elements: a, indices: reverse(a.startIndex..<a.endIndex)) would be the reverse of a.4

GeneratorOf just takes a closure and runs it each time to generate the next value. So var i = 0;var naturals = GeneratorOf({ ++i }) sets naturals to a sequence that counts up from 1 to infinity (or rather, to overflow).

These infinite virtual sequences can be pretty useful. For example, to do the same thing as enumerate, you could write Zip2(naturals, somecollection). Or you could pass your infinite sequence into map or filter to generate further inifinite sequences.

(at the opposite end, if you have a single value, but what a function needs is a Sequence, you can use GeneratorOfOne(value) to create a quick sequence that will just serve up just your one value)

It's not all rainbows and unicorn giggles though. Imagine you did the following:

let r = 1...10_000
mapped = map(r) { megaExpensiveOp($0) }

let a1 = mapped
let a2 = mapped

Here the lazy evaluation will work against you. megaExpensiveOp will be run not ten but twenty thousand times.

“Shouldn't map cache the data?” you ask. Well that leads to the next complication. Take this code:

var i =0
let mapped = map(1...5) {
    i += 1
    return $0 + i
}

Every time you iterate over mapped now, you'll get different results.5

This behaviour might be put to very good use (say you wanted to peturb a data set with small random values). But if you weren't expecting it, that could be one nasty bug to track down.

So its good to know when you're using these functions what they are actually doing under the hood. Just keep in mind these caveats and an exciting life of lazy evaluation awaits you in the off-world colonies.


  1. OK I cheated, first_n isn't a Swift standard library function. But it should be! 
  2. This code would look a lot nicer if Swift came with a pipe operator 
  3. Yeah, this is a pretty rubbish example, I should have put the time in to think of a better real-life use case. 
  4. Obviously, reverse(a) would work better, but a more useful example is tough to fit on one line… 
  5. If you're unclear on how come, try reading this article

Changes to the Swift Standard Library in Beta 3

Xcode Beta 3 came out today, and with it a new version of the Swift standard library.

By far the majority of changes are to account for the publicized updates to the language:

  • replacing Type[] with [Type], and making use of the new [Key:Val] sugar for dictionaries
  • switching uncheckedArithOp for arithOpWithOverflow in all the numeric types
  • adding explicit bigEndian and littleEndian initializers to the integers
  • replacing succ and pred with successor and predecessor1
  • adding sorted as an operation on arrays and as a standalone algo, since sort now sorts in-place2

copy and unshare have been removed from Array, since they’re redundant now arrays have full value semantics. Assigning an array to another variable copies it. Or rather, it lazily copies it – the array will only by physically copied when you alter one of the elements. So really, the equivalent of unshare is called automatically when any value in the copied array or the copy is altered. You can still detect when this happens with the === operator, which returns true if two arrays are pointing to the same underlying store:

var a = [1, 2, 3, 4]
let b = a  // 'a' is "copied"
// but really, it's still the same
a === b    // returns true
a[2] = 2   // until you alter 'a'
// and now they're different
a === b    // returns false

This is really important to understand, in case you start to panic about all the unnecessary copying that might happen when you pass an array into a function as a parameter.

There are also a handful of other changes/additions that aren’t mentioned in the release notes.

Range now supports map as a member, so you can write (1...5).map { $0 * 2 } much like with an Array, rather than map(1...5) { $0 * 2 }. Note, Range.map returns an Array, unlike the map algorithm, which returns a lazily-computed view class.

Lots more types (such as Range) now have a getMirror() method.

min and max, which previously took two or more parameters (the “more” part being a variadic parameter) now have an overload with just two parameters. This means you can pass them as an argument to another function that expects a binary operator. So the following now compiles where previously it would throw an error:3

let a = [5, 3, 1, 7, 9]
let b = [2, 4, 1, 1, 7]

// now you can write this:
let mins = map(Zip2(a, b), min)

// instead of being forced to write this:
let mins = map(Zip2(a, b)) { min($0, $1) }

Finally, the already mysterious insertionSort got a bit more mysterious.

Previously there were two versions, both of which required a collection with a bidirectional index. One just required that the collection contents be comparable. The other allowed the caller to supply a predicate to compare elements with. That’s a pretty standard pattern, but oddly that predicate is declared inout. Why a sort algorithm needs to be able to change the caller’s comparison function I do not know, but it can!4

The new insertionSort that doesn’t take a predicate now requires a random-access index, rather than a bidirectional index. The version that takes the predicate still only requires a bidirectional index. It’s predicate is still inout though.

There are a few other changes, relating to unicode character processing and Objective-C interfacing, that I either don’t feel qualified to comment on or haven’t delved into. Feel free to mention antyhing interesting about them in the comments.


  1. Bit odd, that, I preferred the shorter versions. 
  2. I really hate they did this to the non-member version, as it means you can’t chain it. 
  3. If you don’t follow what this does – Zip2 takes two sequences and “zips” them together, producing a new sequence that has pairs of elements from the same point in both sequences. map then takes each element of this sequence and applies a function to each one. That function, min, takes the pairs and returns the minimum. So the whole expression returns a sequence of the minimum of each position in either array. 
  4. It does mean you can’t call it with a trailing closure expression. You have to create a variable and point that at a function and then pass that variable in. That can’t be the reason, can it? 

Extending the Swift language is cool, but be aware of what you are using

Features like the @auto_closure keyword in Swift offer a great opportunity to extend the language in ways that might not be possible in other languages. For example, in this article we used it to implement the Ruby ||= operator.

Swift doesn’t yet have a native implementation of unless or until. These are just versions of if or while, but for when the predicate is not true. Obviously you could just stick a ! in front of your if clause, but some programmers prefer the readability of the opposing versions. The implementation of ||= could be rewritten as:

@assignment func ||=<T>(inout lhs: T?, rhs: @auto_closure () -> T) {
    unless(lhs) {
        lhs = rhs()
    }
}

I know, you think, I can implement unless and until myself! What’s nice is you can make them look almost like the native flow control statements, because closure expressions can be outside the parentheses of function calls if they are the last argument.1 Implementing unless seems pretty straightforward:

func unless<L: LogicValue>(pred: L, block: ()->()) {
    if !pred {
        block()
    }
}

// doSomething only if condition is false
unless(condition) {
      doSomething()
}

until is a little trickier, because you need to execute the predicate multiple times as you loop. But @auto_closure can help you out.

func until<L: LogicValue>(pred: @auto_closure ()->L, block: ()->()) {
    while !pred() {
        block()
    }
}

// doSomething until condition becomes true
until(condition) {
    doSomething()
}

Now, the conditional expression passed as the first parameter to until will be automatically wrapped up into a closure expression and can be called each time around the loop. Any variable used in both the parentheses and the block will be captured by both, so altering it in the block will affect the result of the condition (hence the condition can become true over time).

Armed with your new unless and until functions, you write a function to search a collection for the index to the first occurrence that doesn’t match a predicate:2

func findIfNot
  <C: Collection, L: LogicValue>
  (col: C, pred: (C.GeneratorType.Element) -> L)
  -> C.IndexType? {

    var idx = col.startIndex
    until(idx == col.endIndex) {
        unless(pred(col[idx])) { return idx }
        idx = idx.succ()
    }
    return nil
}

let a = [1, 2, 3]
let isOdd = { $0%2 == 1}
// find the first non-odd number
let idx = findIfNot(a, isOdd)

Arguments about SESE and other stylistic preferences aside, this function should do the job. Except instead it generates a compiler error, 'C.IndexType' is not convertible to '()'.

Why? Because the return after the unless is a return from that closure expression between the braces, not a return from the findIfNot function. That unless closure expects no value to be returned, so when you return idx it’s an error. But if you were just blithely using this unless function you found in a library as if it were just like an if statement, you might not realize this and the compiler error may come as a shock.

Now say you instead implemented findIfNot to take in an index into the collection as an inout, and advanced that index to the first non-match, instead of returning a value (and returning the endIndex if every item matches). This is pretty bad code, but here it is:

func findIfNot
  <C: Collection, L: LogicValue>
  (col: C, inout idx: C.IndexType,
  pred: (C.GeneratorType.Element) -> L) {

    until(idx == col.endIndex) {
        unless(pred(col[idx])) { return }
        idx = idx.succ()
    }
}

let a = [1, 2, 3]
let isOdd = { $0%2 == 1}
var idx = a.startIndex 
findIfNot(a, &idx, isOdd)
// idx will not be what you would hope 

Now, no compiler error. Instead, this code will fail much more subtly, always returning as if no non-match was found. If we replace the unless with an if, the code will run forever because the until block will return before moving idx forward, and then loop again.

Unit tests should catch this of course. But as a user of built-in-like functions, you should always be aware they aren’t quite the part of the language they might seem. The bugs resulting might not be as obvious as in this case. Also, this is a good argument for using a more “functional“ approach, by writing general algorithms like findIfNot rarely and testing them thoroughly, and then reusing them as much as possible, rather than writing explicit loops.

Should Apple extend Swift to cover this kind of case? Maybe a keyword that causes a closure that doesn’t return a value to be able to pass the return statement out and act on the calling function?3 Until they do, this is definitely a gotcha to be aware of.


  1. Sadly your implementions will always be lacking one feature that if or while have – leaving off the brackets around the predicate. You can’t write unless so it can be used as if pred { } – unless Apple extends “if the last parameter is a closure expression you can have it outside the parens” to be “if there are two parameters and the last is a closure expression, you can leave the parens off the first parameter”. 
  2. If you don’t follow what the code here is doing, try reading this introduction to algorithms on collections in Swift. 
  3. If I’ve missed something huge here and there’s already a way around this issue, leave a comment! 

Using multiple dispatch to add different types of numbers

This is part of a series on solving Paul Graham’s accumulator problem in Swift. You can find Part 1 here.

In the previous post, we solved the requirement that our accumulator accept any kind of numeric type, and to “upgrade” the type it returns from an integer to floating point only the first time it is called with a floating point number. The solution was to use the Swift Any type:

func foo(var n: Any) -> (Any) -> Any? {
    return { incf(&n, $0) }
}

There were lots of flaws with this approach, the worst of which was the loss of type-safety that comes with using Any. The user of foo can pass anything into the accumulator – a String, a Range, any user-defined Class. Our solution to this was to have incf return nil for types it didn’t understand. But it would be much better to rewrite foo so that it just wasn’t possible to call it with an unsuitable type in the first place.

One way would be to create a Number class and use that. But then users of the accumulator would have to explicitly convert their variables and literals to this class before using it (as Swift doesn’t support implicit conversion).

Intead, we can create a protocol Number, and extend both Int and Double to support it. Something like this:

protocol Number {
    func plus(rhs: Number) -> Number
}

extension Int : Number { ... }
extension Double : Number { ... }

Then rewrite the accumulator generator to use it instead of Any:

func foo(var n: Number) -> (Number) -> Number {
    return { n = n.plus($0); return n }
}

Now foo can be called with an Int or a Double, but can’t be called with any other type that doesn’t implement the Number protocol. The method plus would act polymorphically, adding either kind of number to an existing one, and upgrading from Int to Double when needed.

How do we implement the plus method? It needs to execute different code depending on both the type of the current value and the type of the value being added to it. That is, the behaviour of plus needs to be polymorphic with respect to two different objects, not just one. This requires something called “multiple dispatch” (in this case, specifically double dispatch).

Ordinarily, Swift (and most other OO languages) only alter their behaviour at runtime based on one object – the object who’s method is being called. This is known as single dispatch. But there is a technique that allows us to implement double dispatch. First, we need to add more methods to the Number protocol:

protocol Number {
    func plus(rhs: Number) -> Number
    func plus(rhs: Int) -> Number
    func plus(rhs: Double) -> Number
}

Then, we implement them for Int and Double like this:

extension Int : Number {
    func plus(rhs: Number) -> Number {
        // re-call plus with an Int parameter this time
        return rhs.plus(self)
    }

    func plus(rhs: Int) -> Number {
        // an Int plus an Int is an Int
        return self + rhs
    }

    func plus(rhs: Double) -> Number {
        // an Int plus a Double is a Double
        return Double(self) + rhs
    }
}

extension Double : Number {
    // re-call plus with a Double parameter this time
    func plus(rhs: Number) -> Number {
        return rhs.plus(self)
    }

    func plus(rhs: Double) -> Number {
        // a Double plus a Double is a Double
        return self + rhs
    }

    func plus(rhs: Int) -> Number {
        // a Double plus an Int is a Double
        return self + Double(rhs)
    }
}

How does this work? The interesting part is the implementation of plus that takes a Number. This calls plus again, but not recursively – instead it calls it on the right-hand side object, passing self in as a paramter. Because at this point, the code is inside a definitive type (either an Int or a Double), self will be one of those types rather than the abstract Number, and it will call one of the methods lower down.

We can easily test this works for all combinations:

let combos: Array<(Number,Number)> = [
    (1, 1),
    (1.1, 1.1),
    (1, 1.1),
    (1.1, 1),
]

for (a, b) in combos {
    println("\(a) + \(b) = \(a.plus(b))")
}

prints out:

    1 + 1 = 2
    1.1 + 1.1 = 2.2
    1 + 1.1 = 2.1
    1.1 + 1 = 2.1

Fun as this technique is, as Bjarne Stroupsrup says, “if you consider this elegant, you need to raise your standards, but it gets the task done”. Accumulators generated with this code can take either integers or floating point numbers, and ones that have only seen integers return integers, and you can’t call it with any other unsupported types.

It still suffers from similar problems to the incf solution – every time you add a new type of Number you need to alter the code quite extensively. And implementing additional operations like minus or multiply would require even more code. Looking at a solution to that will be the subject of the next in the series. Follow @AirSpeedSwift to catch it.

Swift’s for loops avoid an easy mistake with variable capture

This article from a while back points out “the biggest mistake everyone makes with closures” in Ruby, Python, Perl and Javascript.1

Try running this code in Ruby, which counts i up from 1 to 3 creating a closure each time which returns the value of i:

a = []
for i in 1..3
  a.push(lambda { i })
end

for f in a
  print "#{f.call()} "
end

and it prints out the possibly surprising value 3 3 3.

Using more “functional” constructs doesn’t always save you. This Python also prints all 3s:2

a = [lambda: i for i in xrange(1, 4)]
for a in f:
  print f()

The article goes on to suggest some workarounds.

Here is the equivalent in Swift:

var a: Array<()->Int> = []

for i in 1...3 {
  a.append( { i })
}

for f in a {
  println("\(f()) ")
}

and happily, this prints 1 2 3.

Note, this also works with references to objects, so if you subsituted a for over a sequence of objects instead of Ints in the code above, each closure would capture a reference to a different object.

Be careful though, this applies to for loops but not to other loops like while or the C-style for(;;), so:

var i: Int = 0
while(++i <= 3) {
    a.append( { i })
}

for f in a {
    print("\(f()) ")
}

prints out 3 3s.

Why is this? Is this a special hack to make for...in behave less surprisingly? To understand why it does this, you need to realize that this:

for i in 1...3 {
  a.append( { i })
}

is just a shorthand equivalent to writing this code using the source sequence’s generator:

var g = (1...3).generator()
while let i = g.next()
  a.append( { i })
}

The answer to our question lies in the let i =, which declares a fresh variable i for each iteration of the loop, hence if you capture i, it will retain its value at the end of the block. If you use this form of while loop, you’ll get the same results as with the for...in version.


  1. Go here for an epic list of how other languages handle this issue. 
  2. The Ruby each will do something similar in version 1.8, though it was altered in 1.9 to behave differently which is somehow more scary. 

Writing Algorithms on Collections in Swift

edit: this post has been updated to Swift as of Xcode 6.1 (Swift 1.1).

Suppose you want a new algorithm that checks if every member of an array fulfills a given criteria.

Your first thought might be to add it as an extension of Array:1

extension Array {
    func all_of<B: BooleanType>
        (predicate: (Element) -> B) -> Bool {
            for e in self {
                if !predicate(e) {
                    return false
                }
            }
            return true
    }
}

This function takes a predicate (a function that takes an element and returns true or false), and applies it to every member of the array, only returning true if it was true for every member.

Note we specify a template argument, B: BooleanType, that allows the predicate to return not just a Bool but any type that can behave like a Bool (such as ObjCBool)2.

We can test it works easily:

let isEven = { ($0 % 2) == 0 }
let mixed = Array(1...4)     // [1, 2, 3, 4]
let doubled = map(1...4) { $0 * 2 }
let evens = Array(doubled)   // [2, 4, 6, 8]

mixed.all_of(isEven)  // false
evens.all_of(isEven)  // true

Incidentally, the above shows a nice trick that’s useful for testing collection algorithms, which is that arrays can be initialized with sequences, such as ranges. So if you quickly want an array of increasing numbers, you can write Array(begin...end). If you want something more complicated, you can pass a range to map or filter to alter the range first.

This implementation is nice because it’s now built into Array, but there are a few downsides.

Firstly, what if you wanted a slightly different version all_of_equal, that just took a value and confirmed if every entry was equal to that value? You’ll need to test for equality, so Element will need to be Equatable. You might think you’d specify a function that goes like this:

extension Array {
    func all_of_equal<Element: Equatable>
    (value: Element) -> Bool {
        return self.all_of { $0 == value }
    }
}

Nope, that won’t work. The problem is that you can’t further constrain Element within Array to be Equatable. What if you created an array of something that didn’t conform to Equatable? Would this no longer be allowed now you’ve added this method? Or should this method not be callable? Neither of these are palatable so the language just won’t let you do it.

Instead, you need to define a non-member function that takes an Array and an Element. Then you can constrain that element as much as you like:

func all_of<E, B: BooleanType>
    (a: Array<E>, predicate: (E) -> B) -> Bool {
        for e in a {
            if !predicate(e) {
                return false
            }
        }
        return true
}

func all_of_equal<E: Equatable>
    (a: Array<E>, rhs: E) -> Bool {
        return all_of(a) { $0 == rhs }
}

In fact, because of Swift’s operator overloading, you can even give it the same name:

func all_of<E: Equatable>
    (a: Array<E>, rhs: E) -> Bool {
        return all_of(a) { $0 == rhs }
}

// calls the version that takes an equatable value
all_of([1,1,1], 1)

// calls the version that takes a closure
all_of([1,1,1]) { $0%2 == 1 }

The second benefit of defining this as a non-member function is you can generalize it to apply not just to arrays, but any kind of collection.3 To do this, you need to extend the generic parameter clause in a couple of ways:

func all_of<E, C: CollectionType, L: BooleanType
    where E == C.Generator.Element>
    (c: C, predicate: (E) -> L) -> Bool {
        for e in c {
            if(!predicate(e)) {
                return false
            }
        }
        return true
}

First, we swap out Array for a type of Collection, by specifying a generic placeholder C that must be a collection. Then, we further constrain the collection to contain types E, which are the type of input our predicate will take.

Strictly speaking, we don’t need to include the placeholder E. You could replace it in the predicate definition with C.Generator.Element. But you might find it’s cleaner to create a placeholder for it, especially if you apply further constraints to E.

Now, we can use this function on not just arrays, but any type of collection, such as ranges directly:

let isEven = { ($0 % 2) == 0 }
all_of(1...4, isEven)  // returns false

or other types of collection:

let doubled = map(1...4) { $0 * 2 }
all_of(doubled, isEven)  // returns true

There’s one final improvement that could be made. Collections implement the Sequence protocol, which also gives us enough to iterate over the elements, checking the predicate. So we could rewrite all_of even more generally:

func all_of<E, S: SequenceType, B: BooleanType
where E == S.Generator.Element>
(sequence: S, predicate: (E) -> B) -> Bool {
    for e in sequence {
        if(!predicate(e)) {
            return false
        }
    }
    return true
}

Because Sequences behave differently, we don’t need to mandate a ForwardIndex to make them work with the for.

There are some times you still want to use collections rather than sequences. If we were writing a different algorithm, say find_first_of, that we wanted to return an index into the collection of the first occurrence, we’d want to stick with an algorithm that works on collections. Also, collections imply deterministic results over multiple iterations, and consistent size, which some algorithms might rely on. But not in the case of all_of, so SequenceType is a better choice.


  1. The most important question facing the Swift community today: how do you split long function footprints over multiple lines? 
  2. In fact, the Swift standard library docs explicitly state that Bool and ObjCBool should really only be the two types that ever implement BooleanType, so maybe you could say screw it and just make the predicate return a Bool. That’s what the predicates for std lib functions like filter do. But then, that wouldn’t make for quite so educational a blog post. 
  3. You might be thinking, I know, I’ll extend CollectionType! But CollectionType is a protocol, and you can’t extend protocols with implementations. What you want is something like traits or mixins. Swift doesn’t have those (yet, hopefully). 

Closures and Closure Expressions are two different things

Bit of quick monday morning pedantry. fuckingclosuresyntax.com, while fun and useful, is perpetuating a subtle conflation of two things, that most Swift programmers have silently adopted, that in turn is probably confusing a lot of beginners.

This function returns a closure:

func return_a_closure() -> () -> (Int) {
  acc = i
  func the_closure() -> Int {
    return ++acc
  }
}

Even though func was used to define the closure, not { }, it is still a closure, because it’s a function that captures an environment of variables (in this case acc).

The { } syntax alternative to func is called a “closure expression” but it doesn’t make the function returned any more closurey than the example above.

If you already know the difference, it’s natural to drop the word “expression” and just call them closures, and this is what most people writing about Swift are doing. This was inevitable as soon as Apple decided to call them closure expressions, rather than blocks or lambdas or anonymous functions. But this conflation seems to be confusing a lot of people coming to Swift without a background in first-class function and closures. The opening of the closures chapter in the official Swift book makes the difference quite clear, but still the confusion remains.

The bright side is this might be forcing new developers to learn about closures, by throwing them in the terminology deep end. If Apple had stuck with Objective-C’s term, blocks, maybe fewer programmers would be learning about variable capture (plus, fuckingblocksyntax.com was already taken).

What would have been really cool? If Apple had done away with the func keyword altogether, leaving closure expressions assigned to variables as the only way to declare functions. But that would have pushed way too many people out of their comfort zone.

If all this is nonsense-speak to you, try reading this tutorial.

Implementing some Ruby builtins in Swift

Type 1. into irb and hit tab, and it’ll ask you if you want to see all 105 possibilities. Try it with [ ] and you’ll be offered 155. Ruby comes with a lot of built-in methods on its default types.

It’s debatable how useful all of these are. The idiom in Swift seems much more to be like in the C++ STL, where there are algorithms that operate on collections, rather than collections having methods that operate on themselves. To see more about this, read this article on writing algorithms against collections.

But for the sake of looking at a few Swift language features, let’s implement some of the Ruby popular ones. Maybe they’d be useful making a Ruby refugee feel at home.

First off, the Int loops. Lots of “hey look, ruby is cool” intros kick off with this one:

10.times do |i|
   "ruby is cool!"
end

This is pretty easy to add to the Swift Int using an extension:

extension Int {
    func times(f: () -> () ) {
        for _ in 0..self {
            f()
        }
    }
}

10.times { "swift is cool too!" }

Note the _ instead of a variable in the for, because the value isn’t actually needed.

Next, two for alternatives, upto and downto:

1.upto(3) {|i| print "#{i}.. "} # prints 1.. 2.. 3..
3.downto(1) {|i| print "#{i}.. "} # prints 3.. 2.. 1..

in Swift would be:

extension Int {
    func upto(n: Int, f: (Int) -> () ) {
        for i in self...n {
            f(i)
        }
    }
    func downto(n: Int, f: (Int) -> () ) {
        for i in reverse(n...self) {
            f(i)
        }
    }
}

Note the use of the inclusive ... this time, unlike with times which used the convention of a zero base up to but not including n so needed non-inclusive .., because this time we want to start at self and count inclusively to n. Humorously, Ruby also has inclusive and exclusive ranges but .. and ... are the opposite way around.

For downto, the range is wrapped in a reverse in order to count backwards.

Next, some extensions to array, in a similar vein to map or reduce.

Ruby’s each is like map, but doesn’t generate any return value:

extension Array {
    func each(f: (Element) -> ()) {
        for e in self {
            f(e)
        }
    }
}

Element is a Type Property representing the type of value the Array contains, to this function works generically for type contained by array.

Ruby’s reverse_each does the same but in the opposite direction:

extension Array {
    func each(f: (Element) -> ()) {
        for e in Swift.reverse(self) {
            f(e)
        }
    }
}

Again, we use reverse to go backwards through the array. Wait, you might think, isn’t it inefficient to reverse the array just to iterate over it? But that’s not what reverse does – instead it generates a lazy collection that serves up the values in reverse order.

Note, we have to prefix it Swift.reverse to disambiguate it from the Array member function reverse – which would result in creating a whole new array in reversed order, if we used it.

Ruby’s delete_if is the opposite of Swift’s filter – it takes a discriminator function and returns any elements that don’t match. We could easily just implement it from scratch with a for loop, but instead let’s try and implement it by re-using filter.

One way to do this is to first create what’s called a “decorator”. Decorators are functions that take other functions, and return a new function that has changed the behaviour of the original function in some useful way.

What we want is a decorator that takes a function that returns a boolean, and then returns the opposite of that. Here it is:

// function that takes a function, f, that takes an element
// and returns a bool, and returns a function that applies f
// then returns the opposite
func not_f<T>(f: (T)->Bool) -> (T)->Bool {
    // this returns a closure that captures f
    return { !f($0) }
}

If you’re a bit hazy on closures and variable capture, read this.

Armed with not_f, we can define delete_if:

extension Array {
    func delete_if(f: (Element) -> Bool) -> Element[] {
        return self.filter(not_f(f))
    }
}

Finally, Ruby’s equivalent of filter is called select. It’s identical, it’s just called by a different name. Is there some way we could alias filter if we wanted?

Yup, like this:

extension Array {
    var select: ((Element) -> Bool) -> Element[] { 
        return Array.filter(self) 
    }
}

You can now use select in exactly the same way you use filter. This is quite a silly thing to do, but it does demonstrate a couple of language features: read-only computed properties that return closures, and references to member functions.

Read-only computed properties are used like regular properties i.e. can be accessed using the dot syntax, but behave like functions that take no arguments and return a value. In this case we have defined a property select that returns a function when you call it. We’re just returning an existing member function (more on that next) but you could have more complex logic that created and returned different kinds of closures.

The reason it’s nice to implement these as computed properties is you don’t need to use a () after the property name. This means if you want to compute a function for someone to use, they can use it like this: x.computedfun(). If computedfun was itself a function, you’d have to write this: x.computedfun()(), which looks odd. Other than that, they behave just like functions that return functions.

So what is select actually returning? To understand that, you need need to realize you can reference a classes’ member functions. See the following code:

class MyClass {
    let n: Int

    init(_ i: Int) { n = i }

    func multiply(i: Int) { 
        println("n: \(n) * i: \(i) = \(n*i)")
    }

    func add(i: Int) { 
        println("n: \(n) + i: \(i) = \(n*i)")
    }
}

let a = MyClass(2)
let b = MyClass(5)

// prints "n: 2 * i: 10 = 20"
a.multiply(10)

// prints "n: 5 + i: 10 = 50"
b.add(10)

// this takes a reference to the member 
// function multiply of MyClass
var memfunref = MyClass.multiply

// you can't use memfunref directly.
// you have to apply an instance of
// MyClass to it:
var instancefunref = memfunref(a)

// now you can call it, and it's
// like calling a.multiply, so
// this prints "n: 2 * i: 10 = 20" 
instancefunref(10)

// MyClass.add has the same type as
// MyClass.multiply, they're both (Int)->(),
// so you can assign it to memfunref too:
memfunref = MyClass.add

// and apply a different instance of MyClass
instancefunref = memfunref(b)

// this prints "n: 5 + i: 10 = 50"
instancefunref(10)

// or you can skip the instancefunref step
// prints "n: 5 + i: 10 = 50" again
memfunref(b)(10)

Now we can see what that computed property is doing. It’s returning the member function filter of Array, then applying self to it, and returning that. The caller then can call the returned function () and it runs filter against the object they fetched it from. Like I said, bit silly, but it demonstrates a feature that could probably be put to better use in other cases.

If you liked this post, this one is also about implementing Ruby features in Swift, in this case implementing the ||= operator using the @auto_closure Swift feature.