Skip to content

Instantly share code, notes, and snippets.

@Edudjr
Last active June 6, 2019 22:37
Show Gist options
  • Save Edudjr/c67aadaa7b53a622fb01fb0c642083f0 to your computer and use it in GitHub Desktop.
Save Edudjr/c67aadaa7b53a622fb01fb0c642083f0 to your computer and use it in GitHub Desktop.
This is a currying example for Swift 4.2
func sum(v1: Int, v2: Int) -> Int {
return v1 + v2
}
func sub(v1: Int, v2: Int) -> Int {
return v1 - v2
}
func operation (_ operation: @escaping (Int, Int) -> Int) -> (Int, Int) -> Int {
return { v1, v2 in
operation(v1, v2)
}
}
func multiple(_ operations: ((Int, Int) -> Int)...) -> (Int, Int) -> [Int] {
return { v1, v2 in
operations.map({ op in
op(v1,v2)
})
}
}
let sumOp = operation(sum) // (Int, Int) -> Int
let subOp = operation(sub) // (Int, Int) -> Int
operation(sum)(4,2) // 6
operation(sub)(4,2) // 2
sumOp(4,2) // 6
subOp(4,2) // 2
multiple(sumOp,subOp)(4,2) // [6,2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment