Swift - Function as parameter

Introduction

Functions can receive and use other functions as parameters.

This means that you can combine functions:

Demo

func timesThree(number: Int) -> Int { 
    return number * 3 
} 
func doSomethingTo(aNumber: Int, thingToDo: (Int)->Int) -> Int { 
    return thingToDo(aNumber) 
} 
// Give the  'timesThree' function to use as  'thingToDo' 
var a = doSomethingTo(aNumber: 4, thingToDo: timesThree) // 12 
print(a)//from w w  w. j ava 2  s. c  o  m

Result

Here, doSomethingTo function received some function as a parameter.

It refers it as as 'thingToDo' inside the function.

Call the function 'thingToDo' using 'aNumber', and return the result.

Related Topic