Using functions as parameters

A function can take a function as a parameter.

 Type in and run the following code:

// functions can have functions as parameters
func isThereAMatch(listOfNumbers: [Int], condition:
(Int) -> Bool) -> Bool {
for item in listOfNumbers {
if condition(item) {
return true
}
}
return false
}
// this function determines if a number is an odd number
func oddNumber(number: Int) -> Bool {
// number % 2 returns 1 for odd, 0 for even
return (number % 2) > 0
}
var numbersList = [2, 4, 6, 7]
isThereAMatch(listOfNumbers: numbersList, condition: oddNumber)
// since numbersList has 7 in it, true will be returned

isThereAMatch(listOfNumbers:, condition:) takes two parameters: an array of integers and a function. The function provided as a parameter must take an integer value and return a Boolean. oddNumber(number:) takes an integer and returns true if the number is an odd number, which means it can be a condition: parameter for isThereAMatch(listOfNumbers:, condition:). numbersList, an array containing an odd number, is used for the listOfNumbers: parameter. Since numbersList contains an odd number, isThereAMatch(listOfNumbers:, condition:) will return true when called.

In the next section, you'll see how you can perform an early exit on a function if the parameters used are not suitable.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.123.106