Skip to content

Instantly share code, notes, and snippets.

@asefnoor
Created October 5, 2019 22:45
Show Gist options
  • Save asefnoor/3ad9094481bb910910265c811be3f4d8 to your computer and use it in GitHub Desktop.
Save asefnoor/3ad9094481bb910910265c811be3f4d8 to your computer and use it in GitHub Desktop.
Closures understanding
import UIKit
//Closures: Functions can be passed into another functions as parameters and can be returned from functions as well.
// Step 1
//func calculate (n1: Int, n2: Int) -> Int {
// return n1 * n2
//}
func add (no1: Int, no2: Int) -> Int {
return no1 + no2
}
func multiply (no1: Int, no2: Int) -> Int {
return no1 * no2
}
//Step: 2
//now lets pass this func as parameter to calculate function step 1
//func calculate (n1: Int, n2: Int, operation: (Int, Int) -> Int) -> Int {
// return n1 * n2
//}
//Now lets change the body of the Step 2 function to call the function that we passed
func calculate (n1: Int, n2: Int, operation: (Int, Int) -> Int) -> Int {
return operation (n1, n2)
}
//Now pass operation func as param
//calculate(n1: 2, n2: 3, operation: add)
calculate(n1: 2, n2: 3, operation: multiply)
//Steps to convert func into closure with following example
func test (no1: Int, no2: Int) -> Int {
return no1 + no2
}
// step a: remove func keyword, remove func name,
//(no1: Int, no2: Int) -> Int {
// return no1 + no2
//}
// step b: move start bracket at start and replace it with in keyword
// {(no1: Int, no2: Int) -> Int in
// return no1 + no2
//}
//Now lets replace closure in function call
// one must be thinking why we replaced in function call, well because we want this function to be called from within the calculate body
//calculate(n1: 2, n2: 3, operation:{(no1: Int, no2: Int) -> Int in
// return no1 + no2
//})
//We can simplify it by removing datatype in func call params
//calculate(n1: 2, n2: 3, operation:{(no1, no2) -> Int in
// return no1 + no2
//})
//We can simplify it further by removing the return type as compiler can infer the return type from return statement below
//calculate(n1: 2, n2: 3, operation:{(no1, no2) in
// return no1 + no2
//})
// we can also remove return keyword as compiler can infer that closure is performing some func and it means return
//calculate(n1: 2, n2: 3, operation:{ (no1, no2) in no1 + no2 } )
// We can further simplify it because $0 means first param, $1 means second param
//let result = calculate(n1: 2, n2: 3, operation:{ $0 * $1 } )
//print(result)
//If last param is closure then we can omit its name and close the input section with closing bracket and remove the trailing bracket
let result = calculate(n1: 2, n2: 3) { $0 * $1 }
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment