Problem Statement
Explain function composition in Swift (combining functions) and how it helps build reusable pipelines of operations on data.
Explanation
Function composition means combining simple functions to build more complex ones. For instance if you have `func double(_ x: Int) -> Int { return x * 2 }` and `func addThree(_ x: Int) -> Int { return x + 3 }`, you could compose them into `func doubleThenAddThree(_ x: Int) -> Int { return addThree(double(x)) }`. /n/n In Swift you can write helper functions like `func compose<A,B,C>(_ f: @escaping (B) -> C, _ g: @escaping (A) -> B) -> ((A) -> C) { return { x in f(g(x)) } }`. /n/n Composition helps build pipelines of operations (e.g., filtering, transforming, mapping) and leads to concise, readable, maintainable code especially when handling data flows in Swift.
Practice Sets
This question appears in the following practice sets: