Avoid using var with this one weird trick

update: as of Swift 1.2, there is another way to do this, as you can now defer assignment to let.

Ever find yourself having to use var when a let would be better, because you’re having to choose between multiple options?

var direction: Direction
switch (char) {
    case "a": direction = .Left
    case "s": direction = .Right
    default:  direction = .Forward
}

var cry: String
if direction == .Forward {
    cry = "To glory!"
}
else {
    cry = "Tum-tee-tum"
}

Often you’ll see people declaring those vars as optionals set to nil, because they think you have to give it a value. This isn’t actually necessary – so long as the compiler can tell it will always be assigned to before it is used, as it is here, it’ll let you defer setting the value. But you still can’t use let instead of var.

Most people are aware of the ternary operator, that means you can replace the if version with this:

let cry = direction == .Forward ? "To glory!" : "Tum-tee-tum"

But this doesn’t scale at all well with multiple choices:

// hours of code formatting enjoyment available making this look sensible
let direction: Direction =
    char == "a" ? .Left
  : char == "s" ? .Right
  :               .Forward

But don’t despair, there’s a better way! Just wrap your switch in a closure expression:

let direction: Direction = { 
// you could put "_ -> Direction in" here instead of
// typing the let, if you prefer

    switch (char) {
    case "a": return .Left
    case "s": return .Right
    default:  return  .Forward
    }

}() // call the expression immediately

There, both sanity and let preserved.

Of course, it’d be nice if there were a version of switch (and maybe even if) that was an expression, so you didn’t need the closure. Especially if it meant Swift could fully infer the type for you (with the closure trick, you have to give the type).

So that’s on my letter to Father Christmas. What would be really nice would be something like this:

let direction = case(char) {
    when "a" { .Left }
    when "s" { .Right }
    otherwise { .Forward }
}

Calling the outer keyword case (and the default otherwise) is lifted from LISP. This would help differentiate it from the switch statement format, to avoid confusion and backwards-compatibility troubles. Ditching the : and replacing it with braces seems more consistent with the rest of Swift syntax rather than sticking with a hangover from C.1 The blocks against the when clauses could follow the same pattern as closures, i.e. automatically return if they’re single expressions.2 The compiler would need to detect when the clauses returned incompatible types and throw an error (the ternary operator behaves similarly).

Anyway, there’s a glass of sherry waiting for Santa if he visits.3 In the meantime, give the closure trick a go.


  1. This idea courtesy of @OldManKris 
  2. Maybe they should even be closures (and you could pass function names instead), not sure about this one. 
  3. I think the Swift dev team have posted on the forums acknowledging switches-as-expressions would be useful and that they’ll probably get to it some time. 

zipWith, pipe forward, and treating functions like objects

In the previous article, about implementing the Luhn algorithm using function composition in Swift, I had a footnote to the part about using mapEveryNth to double every other digit:

An alternative could be a version of map that cycled over a sequence of different functions. You could then give it an array of two functions – one that did nothing, and another that did the conversion.

This post is about doing just that. I’ll define some more generic helper functions, and then use them to build a variant of our checksum function.

First up: cycling through a sequence multiple times. Suppose you have a sequence, and you want to repeat that sequence over and over. For example, passing in 1...3 would result in 1,2,3,1,2,3,1,...etc.

You could do this by returning a SequenceOf object that takes a sequence, and serves up values from its generator, but intercepts when that generator returns nil and instead just resets it to a fresh one:

func cycle
  <S: SequenceType>(source: S) 
  -> SequenceOf<S.Generator.Element> {
    return SequenceOf { _->GeneratorOf<S.Generator.Element> in
        var g = source.generate()
        return GeneratorOf {
            if let x = g.next() {
                return x
            }
            else {
                g = source.generate()
                if let y = g.next() {
                    return y
                }
                else {
                    // maybe assert here, if you want that behaviour
                    // when passing an empty sequence into cycle
                    return nil
                }
            }
        }
    }
}

// seq is a sequence that repeats 1,2,3,1,2,3,1,2...
let seq = cycle(1...3)

This code does something that might be considered iffy – it re-uses a sequence for multiple passes. Per the Swift docs, sequences are not guaranteed to be multi-pass. However, most sequences you encounter from day-to-day are fine with multiple passes. Collection sequences are, for example. But some non-collection sequences like StrideThrough ought to be too. My (possibly misguided) take on this: it seems OK to take multiple passes over a sequence, so long as you make it clear to the caller that this will happen. The caller needs to know if their sequence allows this, and if they pass a sequence that doesn’t support it, the results would be undefined.1

OK, next, suppose you have two sequences. Maybe they’re both finite, maybe one is finite and one infinite (such as a sequence created by cycle above). You want to combine the elements at the same point in each one together, using a supplied function that takes two arguments. We’ll call that zipWith, and it’s very simple:

func zipWith
  <S1: SequenceType, S2: SequenceType, T>
  (s1: S1, s2: S2, combine: (S1.Generator.Element,S2.Generator.Element) -> T) 
  -> [T] {
    return map(Zip2(s1,s2),combine)
}

// returns an array of 1+1,2+2,3+3,4+4,5+5,
// so [2,4,6,8,10]
zipWith(1...5, 1...5, +)

How does this work? Zip2 is a SequenceType that takes two sequences, and serves up elements from the same position in each as a pair.2 For example, if you passed it [1,2,3] and ["a","b","c"], Zip2 would be a sequence of (1,"a"), (2,"b"), (3,"c"). If one sequence is longer than the other, Zip2 stops as soon as it’s used up the shortest sequence.3

Then, that zipped sequence of 2-tuples is passed into map, along with the combiner function. Map does it’s thing, calling a transformation function on each element to produce a new combined value. Remember, Swift functions that take n arguments can instead take one n-tuple. That is, if you have a function f(a,b), and a pair p = (x,y), you can call f as f(p). So if Zip2 produces p = (1,1), then +(p) returns 2.

Finally, map spits out the array of combined pairs, and that’s returned.

So, we have a function that cycles over a given sequence forever, and a function that takes two sequences and combines their elements using a given function. How does this help double every other number in a sequence?

Well, suppose you had a sequence of two functions: one that did nothing, just returned its input unchanged, and one that doubled its input. If you cycled that sequence, you’d have an infinite sequence of functions that alternated between doing nothing and doubling.

How could zipWith be used to combine that cycling pair of functions, with a sequence of numbers, such that every other number was doubled? What would the combiner function need to be? It would have to take a value (the number), and a function (do-nothing or double), and apply the function to the number.

We’ve already written a function that does that, last time: pipe forward.

infix operator |> {
    associativity left
}

public func |> <T,U>(t: T, f: T->U) -> U {
    return f(t)
}

So, if we passed in pipe forward as the function to zipWith, it’d do exactly what we want:4

// a function that does nothing to its input
func id<T>(t: T) -> T {
    return t
}

// a function that doubles its input
func double<I: IntegerType>(i: I) -> I {
    return i * 2
}

// an array of those two functions, for Ints:
let funcs: [Int->Int] = [id, double]

// double every other number from one to ten
// returns [1,4,3,8,5,12,7,16,9,20]
zipWith(1...10, cycle(funcs), |> )

Finally, let’s implement the new checksum function. We’re going to re-use the , mapSome, toInt, sum and isMultipleOf functions from the previous article, just redefining the digit-doubling part:

let doubleThenCombine = { i in
    i < 5
        ? i * 2
        : i * 2 - 9
}

let idOrDouble: [Int->Int] = [
    id,
    doubleThenCombine,
]

let doubleEveryOther: [Int]->[Int] = { zipWith($0, cycle(idOrDouble), |> ) }

let extractDigits: String->[Int] = { mapSome($0, toInt) }

let checksum = isMultipleOf(10) • sum • doubleEveryOther • reverse • extractDigits

let ccnum = "4012 8888 8888 1881"
println( checksum(ccnum) ? "👍" : "👎" )

This shows another benefit of the function composition approach. We completely changed the way the doubleEveryOther function was implemented, but because its interfaces in and out remained the same, everything else could stay untouched. Compare this with the iterative version, where looping and doubling and summing were all tangled up together.

So that’s nice, but you might ask if this version is any better than the version from the last post that used mapEveryNth. And it probably isn’t.

But what it does do is show the power of treating functions like any other object, storing them in a collection and iterating over them.

Suppose the Luhn algorithm actually required you to double the even-positioned numbers, but halve the odd ones. Using the mapIfIndex function, you’d need to take two passes (or write another function that took two transformations). With the zipWith technique, all you’d have to do is replace id with a function to halve its input.

You could take this even further. In this example, the array was built literally. But imagine a scenario where you needed more dynamic behaviour – where the array of functions you passed into zipWith were built at runtime, perhaps chosen via user interaction.

“Big whoop,” you say. “This is just like an array of delegates. I’ve been doing this for years.” And that’s totally fair. But functions can be both lighter-weight and more flexible. No need to create an interface, define methods, create an object that implements the interface, worry about which methods need real implementations and which just need stubbing out. The callee defines the function type, the caller writes a closure expression, maybe captures a few variables, and we’re done. For more on this, see Peter Norvig’s slides on how language features can make design patterns invisible or simpler.5

As ever, you can find all the general-purpose functions defined in this post in the SwooshKit framework.


  1. The alternative to this (which the Swift docs actually advocate) is to only write cycle against collections, not sequences. But this seems like a shame, as it’d rule out using it on sequences that don’t have collection equivalents, like strides, but that ought to be multi-pass capable. Perhaps an option is to create a new protocol, MultipassSequenceType: SequenceType { } and to have sequences that can be used this way extend that? 
  2. Zip2 is a bit of an anomoly in the Swift standard library. Whereas in most places, the pattern is to have a function that returns an object (for example, the enumerate function returns an instance of EnumerateSequence), Zip2 skips that stage and is just a struct itself, that you initialize with two sequences. Its usage looks almost exactly the same, but that’s why the Z is capitalized (because the convention is to capitalize the names of structs). 
  3. If you’re interested in a version of zip that runs to the end of the longer sequence, I used one in this gist
  4. If you’re of a more Haskelly temperament, you might feel this is the wrong way around (functions should come before values because f(x). In which case you’d want pipe backwards (<|) and flip the first two arguments. 
  5. OK, so he was talking about dynamic languages, not just functional ones, but it’s still worth reading. 

A straw man argument for trying more functional-style programming in Swift

A few weeks back, @SwiftLDN ran a hands-on, and the challenge was a calculation of the Luhn checksum for credit card numbers in Swift. Implementing this algorithm features as an early problem to solve in some functional programming tutorials, and can serve as a nice example for contrasting different programming styles.

(If you’re already familiar with more functional-style Swift, you’ll already know about many of the techniques in this article, but I’m also going to use it as a jumping off point to talk more about overloading, and also performance.)

Here’s wikipedia’s description of the algorithm:

  1. From the rightmost digit, which is the check digit, moving left, double the value of every second digit; if the product of this doubling operation is greater than 9 (e.g., 8 × 2 = 16), then sum the digits of the products (e.g., 16: 1 + 6 = 7, 18: 1 + 8 = 9).
  2. Take the sum of all the digits.
  3. If the total modulo 10 is equal to 0 (if the total ends in zero) then the number is valid according to the Luhn formula; else it is not valid.

Let’s start by writing an imperative version, and then getting all judgmental about it:

func checksum(ccnum: String) -> Bool {
    var sum = 0
    var idx = 0
    for char in reverse(ccnum) {
        if let digit = String(char).toInt() {
            if (++idx)%2 == 0 {
                sum += digit < 5
                    ? digit * 2
                    : digit * 2 - 9
            }
            else {
                sum += digit
            }
        }
    }

    return sum % 10 == 0
}

let ccnum = "4012 8888 8888 1881"
println( checksum(ccnum) ? "👍" : "👎" )

This bit of code is perfectly adequate. It already uses some of Swift’s features to make it simpler and safer, such as for ... in, an if let binding to check if the character was a digit, and reverse to reverse the string.

But it’s not totally obvious at first glance that it’s correct. The mutable var sum means you have to run through the whole function in your head to understand what it does, figuring out how sum gets changed over time. Debugging it would probably involve stepping through line by line.

“But this is Swift!”, you say. “We should be avoiding var, and using map and reduce and stuff.” So, maybe something like this:

func checksum(ccnum: String) -> Bool {

    let digits = map(ccnum) {
        String($0).toInt()
    }.filter {
       $0 != nil
    }.map {
       $0!
    }

    let checksumDigits = map(enumerate(reverse(digits))) {
        (idx: Int, digit: Int) -> Int in
        if idx%2 == 0 {
            return digit
        }
        else {
            return digit < 5
                ? digit * 2
                : digit * 2 - 9
        }
    }

    return checksumDigits.reduce(0,+) % 10 == 0
}

let ccnum = "4012 8888 8888 1881"
println( checksum(ccnum) ? "👍" : "👎" )

Well, that’s is a bit of a dog’s breakfast. I’d say it’s worse than the version with the for loop, in terms of readability. But we can fix that.

Let’s start with the first part – the conversion of the string to an array of digits. It contains a force unwrap, often a sign there’s a better way. Needing to map and filter simultaneously is a pretty common problem. Common enough that Haskell has a function that combines the two, called mapMaybe (Maybe in Haskell is like Swift’s Optional type). Like map, it takes a function that transforms the elements, but that function returns an optional, and if it returns nil for an element, that element is not included in the result.

Here’s an equivalent function in Swift, which I’ll call mapSome: 1

func mapSome
  <S: SequenceType, D: ExtensibleCollectionType>
  (source: S, transform: (S.Generator.Element)->D.Generator.Element?)
  -> D {
      var result = D()
      for x in source {
          if let y = transform(x) {
              result.append(y)
          }
      }
      return result
}

let toInt = { (c: Character)->Int? in String(c).toInt() }

let ccnum = "4012 8888 8888 1881"
let digits: [Int] = mapSome(ccnum, toInt)
// digits = [4,0,1,2,8,8,8,8,8,8,8,8,1,8,8,1]

Note, when declaring digits, you have to give the type of [Int], because mapSome is written to work on any kind of container that supports the ExtensibleCollectionType – but you have to specify which type of extensible container you want to use (in this case, an array).2

Next, the part that applies a transformation (doubling, and combining double digits) to every other digit. One way to solve this is with another variant of map that only maps every nth entry.3

In fact you could generalize that even further, and write a map that took a function that determined if a given index should be transformed:

func mapIfIndex
  <S: SequenceType, C: ExtensibleCollectionType 
   where S.Generator.Element == C.Generator.Element>
  (source: S, transform: S.Generator.Element -> S.Generator.Element, ifIndex: Int -> Bool)
  -> C {
    var result = C()
    for (index,value) in enumerate(source) {
        if ifIndex(index) {
            result.append(transform(value))
        }
        else {
            result.append(value)
        }
    }
    return result
}

With this, we can write a version of map that transforms every nth entry:

func mapEveryNth
  <S: SequenceType, C: ExtensibleCollectionType 
   where S.Generator.Element == C.Generator.Element>
  (source: S, n: Int, transform: S.Generator.Element -> C.Generator.Element) 
  -> C {

    // enumerate starts from zero, so for this to work with the nth element,
    // and not the 0th, n+1th etc, we need to add 1 to the ifIndex check: 
    let isNth = { ($0 + 1) % n == 0 }

    return mapIfIndex(source, transform, isNth)
}

let double = { $0*2 }
let doubleEveryOther: [Int]->[Int] = { mapEveryNth($0, 2, double) }

let doubled = doubleEveryOther([1,2,3,4,5])
// doubled = [1,4,3,8,5]

Notice how, in the snippet above, instead of applying the map directly to some values, doubleEveryOther is defined as a function that takes an array of Ints, and returns a new array with every other one doubled. This is then used on an array of Ints. Bear this in mind for later.

Finally, we need to sum the result, and then check it’s a multiple of 10. Functions to do that are easy enough:

func sum
  <S: SequenceType 
   where S.Generator.Element: IntegerType>
  (nums: S) -> S.Generator.Element {
    return reduce(nums, 0) { $0.0 + $0.1 }
}

let summed = sum(1...10) // 55

func isMultipleOf<T: IntegerType>(of: T) -> T -> Bool {
    return { $0 % of == 0 }
}

let isMultipleOfTen = isMultipleOf(10)

isMultipleOfTen(5)  // false
isMultipleOfTen(20) // true

Note this time, isMultipleOf is a function that returns another function – isMultipleOf(10) returns a function that tests whether a number is a multiple of 10. isMultipleOf(5) would return a function that tested if a number were a multiple of 5.

OK so now we have a function that can filter out digits, one that transforms every other value, one that sums integers, and one that checks if the result is a multiple of 10. All we need to do is string them all together.

The simple way would be to store each intermediate result in a variable:

func checksum(ccnum: String) -> Bool {

    let digits: [Int] = mapSome(ccnum, toInt)

    let reversed = reverse(digits)

    let transformed: [Int] = mapEveryNth(reversed, 2) { i in
        i < 5
          ? i * 2
          : i * 2 - 9
    }

    let summed = sum(transformed)

    return isMultipleOf(10)(summed)
}

That’s starting to look good. But those variable declarations are kinda cluttering up the place.

You could ditch the intermediate variables and write the whole thing like this:

func checksum(ccnum: String) -> Bool {

    let doubleAndCombine = { i in
            i < 5
              ? i * 2
              : i * 2 - 9
    }

    return isMultipleOf10(sum(mapEveryNth(reverse(mapSome(ccnum, toInt) as [Int]), 2, doubleAndCombine) as [Int]))
}

Obviously that’s ridiculous – it’s not just impossible to read, it’s impossible to write. It took me a good few minutes plugging away, counting all the parenthesis, like an animal.4

Luckily there’s a handy operator we can define that makes chaining function calls together a lot easier: pipe forward.

It looks like this:

infix operator |> {
    associativity left
}

public func |><T,U>(t: T, f: T->U) -> U {
    return f(t)
}

Read that function definition as “take any value of type T as an argument on the left, and any function that takes type T and returns another value of type U on the right, apply the function to the value and return the result”.

This allows us to pipe the result of one function into the input of another , like so:

// returns 30 (sum of 1 to 5, doubled)
1...5 |> sum |> double

Using this, we can rewrite checksum again:

func checksum(ccnum: String) -> Bool {

    let doubleAndCombine = { i in
        i < 5
            ? i * 2
            : i * 2 - 9
    }

    return ccnum
       |> { mapSome($0, toInt) as [Int] }
       |> reverse
       |> { mapEveryNth($0, 2, doubleAndCombine) as [Int] }
       |> sum
       |> isMultipleOf(10)

}

Here, for the functions that take more than one parameter, we have to wrap them in a closure expression to turn them into a temporary function that takes one parameter, the one coming through the pipeline. To read more about pipe forward, try Kris Johnson’s post about it.

One last take. Instead of using the pipe forward, we could use function composition. We can define an operator that takes two functions and returns a new function that is the result of applying first one, then the other. That is, if f and g are functions that take one argument, we could compose them as a new function h that was equivalent to g(f(x)).

infix operator • {
    associativity left
}

public func • <T, U, V> (g: U -> V, f: T -> U) -> T -> V {
    return { x in g(f(x)) }
}

// define a new function that takes a range of Ints, sums
// them, then doubles the result
let sumThenDouble: Range -> Int = double • sum

sumThenDouble(1...5) // returns 30

Unless you’re too busy being incandescent with rage about someone defining an operator using •,5 you’ll notice that, unlike |>, composed functions read from right to left, to match the order if you wrote the application out in full i.e. g(f(x)). There’s nothing magic about this – it’s just how the • function was defined above, with g as the left-hand argument and f as the right-hand one.

You could also define a pipe backwards operator, <|, to go in a similar direction. The Functional Swift book defines >>> as a composition operator that goes left to right. Pick whichever you prefer – left-to-right might feel more natural because it’s similar to object method calls.

Composition can be very useful in building up new more complex functions out of smaller ones. Recall earlier when we were implementing mapEveryNth, we had to write a small function:

    // add 1 to the index to check if
    // this entry is the nth
    isNth = { ($0 + 1) % n }

Assuming we had a function that incremented a number, we could have used composition to build that function:

func successor<I: _Incrementable>(i: I) -> I {
    return i.successor()
}

let isNth = isMultipleOf(n) • successor

And so, for one final go at writing checksum, assuming all the helper functions above are readily available:

let extractDigits: String->[Int] = { mapSome($0, toInt) }

let doubleAndCombine = { i in
    i < 5
        ? i*2
        : i*2-9
}

let doubleEveryOther: [Int]->[Int] = { mapEveryNth($0, 2, doubleAndCombine) }

let checksum = isMultipleOf(10) • sum • doubleEveryOther • reverse • extractDigits

let ccnum = "4012 8888 8888 1881"
println( checksum(ccnum) ? "👍" : "👎" )

The actual declaration is just a let. The checksum function is composed purely from other functions, some generic, some specific.6

Is this better then our original versions? I think so.7 The definition of checksum looks, to me, to be very readable. Reading from right to left, you extract the digits from the input, reverse them, double every other digit, sum them, and check if that’s a multiple of 10. The individual custom functions can be tested separately to check they work correctly – this approach is especially nice when combined with Swift playgrounds.

You could argue this is all cheating. You could take the same “breaking the problem down” steps with the imperative algorithm I started this blog with. And that’s true – but then I did title this post “a straw man”. And ultimately, you’d really still be circling the functional solution, getting closer to it. That’s what’s nice about Swift’s hybrid approach – it allows you to shift from one style to the other according to your preference.

It also assumes you have a library of re-useable functions just lying around that do stuff like this. But a lot of these kind of libraries already exist. They start with all the functions available in the Swift standard library (about which you can read more on this blog), but you might want to check out Swiftz, LlamaKit, or some of Rob Rix’s micro framworks.

Or you could start your own personal library of reuseable functions as you go along. Mine, with all the functions from this blog, is called SwooshKit and you can find it here.


  1. I realize mapOptional would be the equivalent name to mapMaybe, but to me mapSome sounds better and seems more descriptive of what it actually does. 
  2. The standard library goes the other route – the free map function only returns arrays. There is a trick you can do that allows you to default to arrays if not specified, but still be generic – but I’ll leave that for another time. 
  3. An alternative could be a version of map that cycled over a sequence of different functions. You could then give it an array of two functions – one that did nothing, and another that did the conversion. 
  4. Or a LISP programmer. 
  5. I really like it. The main argument against it is that, while it’s easy to type option-8 (because it looks like a *?) on my keyboard, that’s not the case for everyone e.g. Chinese or Arabic keyboards. I’d be interested in feedback from people affected by this (and not so interested in feedback from people who are ASCII-only fans even on English keyboards 😛 ). 
  6. You could even take it further, and compose a function that did the thumbs up/down conversion (using a further functional equivalent of the ternary operator – the VB programmer in me would call that iif), and then compose that with the println function. But let’s not get silly. 
  7. Except in one, possibly crucial, respect – it’s slower than the imperative version. I’ll cover why in a later post.