Once again I am on the moving office (train) and just wanted to post some of my progress with composing Functional Swift. The idea is simple here: call closures within closures using composition and currying. I am simply making practice sessions more complex by adding layers on top of layers. I feel more comfortable with the concept now and am on chapter 3 of Functional Swift by Objc.io.

 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Composing some functional stuff - adding layers in and using currying

typealias StringChange = (String) -> String

func arrange(repeats: Int, _ closure: @escaping StringChange) -> StringChange {
    return { str in
        let affectedString = "Affected + \(str)"
        let closureResult = closure(affectedString)
        return closureResult
    }
}

let closureExample = { (str: String) in
    return "Messed up ||\(str)||"
}

func arrange2(_ closure: @escaping StringChange) -> StringChange {
    return { str in
        closure(str)
    }
}

let arrangedSTUFF = arrange(repeats: 2, closureExample)("Edit me")
let arrangedSTUFF2 = arrange2(closureExample)(arrangedSTUFF)