I was preparing for my first livestream the other day on the train when I had this crazy idea about creating a kind of dating app story to make learning functional swift with Objc.io’s book more fun and interesting…

I went with it on the livestream but couldn’t seem to get past the mental block of passing in and composing with closures. Naturally I was thinking about it most of the night and woke up, jumped on the train and wrote down a quick example. Mind blocks are fun 😀

So the whole idea here is we’re going to write a function that improves a user’s attributes (such as jawline) and we’ll increment their rating by ‘+1’. It’s a trivial example but it shows how to use escaping closures and how to compose functionally, sort of (I’m getting there, bare with me).

The code is available on bitbucket.


// We're using functional swift here to improve the jawline attribute in our fake tindr app
import Foundation

typealias Attribute = (String) -> String

let closure = {(string: String) in return ""}

func improveAttributes(multiplier: Int, filter: @escaping Attribute) -> Attribute {
    return { str in
        let result = closure(str)
        return result + " has been increased by \(multiplier)"

let improvedJawline = improveAttributes(multiplier: 2, filter: filt)("Jawline")

So as you can see we define our own type called attribute which is a function that we can pass around, return and compose with (kind of like complicated lego). It takes a string as an argument (Look at the function call with “Jawline”) and returns a new, updated string ” has been updated…”.

It’s a simple example but getting used to thinking functionally was, and still is, harder than I thought!

What attributes about yourself would you improve? Isn’t writing your own code so much fun?!

Laurie Gray

Author Laurie Gray

More posts by Laurie Gray

Leave a Reply