At last here is an example of composing functions with closures – the idea is a user sets a rating, it goes up to the cloud and users re-rate it with what they really think 😉 and comes down as a completion handler.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import Foundation

let exampleURL = "http://www.test.com/api/v2/request-rating/user/2030/request-id/12321"

func connectToWeb(withURL url: String, withAttributeRequest: Int) -> Int {
    let formattedURL = URL(string: url)
    guard let url = formattedURL else { return 1 }

    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
        do {
            guard let newData = data else { return 1 }
            guard let json = try JSONSerialization.jsonObject(with: newData, options: .mutableContainers) as? [String: Any] else {
                return 1
            }
            print(json)
        } catch let error {
            print(error)
        }
    }
    task.resume()
}

typealias UserAttributeResult = (Int) -> Int

let goOnlineUpdateResult: UserAttributeResult = { (request: Int) in
    let ratedAttribute = connectToWeb(withURL: exampleURL, withAttributeRequest: request)
    return ratedAttribute
}

func requestResult(_ closure: @escaping UserAttributeResult, then completion: @escaping UserAttributeResult) -> UserAttributeResult {
    return { submittedValue in
        // Go online do stuff
        // Completion
        let calculatedResult = closure(submittedValue)
        return calculatedResult
    }
}

let actualResult = requestResult(goOnlineUpdateResult, then: goOnlineUpdateResult)(2)