將函式作為引數傳遞給另一個函式,從而建立一個高階函式
func multiply2(item: Int)-> Int
{
return (item + 2)
}
let multiply2ToMe = multiply2
// passing the function directly to the function as param
print(math.performOperation(inputArray: arrayToBeProcessed, operation: multiply2ToMe))
輸出:
[3, 5, 7, 9, 11, 13, 10, 8, 6, 4, 102]
類似地,使用 closure
可以實現上述目的
// passing the closure directly to the function as param
print(math.performOperation(inputArray: arrayToBeProcessed, operation: { $0 * 2 }))