Anonymous functions or functions without a name.
func calculator (n1: Int, n2: Int, operation: (Int, Int) -> Int) -> Int {
return operation(n1, n2)
}
func add (no1: Int, no2: Int) -> Int {
return no1 + no2
}
calculator(n1: 2, n2: 3, operation: {(no1, no2) in no1 * no2})
// ==
calculator(n1: 2, n2: 3, operation: {$0 * $1})
// == (if the last parameter in your function is a closure({}로 묶여있는), we can omit the parameter number.
// == Trailing closure
let result = calculator(n1: 2, n2: 3) {$0 * $1}
print(result)
>>> 실행결과
6
let array = [6, 2, 3, 9, 4, 1]
func add0ne (n1: Int) -> Int {
return n1 + 1
}
array.map(add0ne)
// ==
array.map({$0 + 1})
// ==
array.map{$0 + 1}
>>>
[7, 3, 4, 10, 5, 2]
array.map{"\($0)"}
>>>
["6", "2", "3", "9", "4", "1"]