random
random

Reputation: 8608

Passing func as param Swift

I am moving through the Swift Programming Language Book and I don't fully understand this:

//I don't understand 'condition: Int -> Bool' as a parameter, what is that saying?
func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool {

    //So here i see we are iterating through an array of integers
    for item in list {

        //I see that condition should return a Bool, but what exactly is being compared here? Is it, 'if item is an Int return true'??
        if condition(item) {
            return true
        }
    }

    return false
}


//This func I understand
func lessThanTen(number: Int) -> Bool {
    return number < 10
}

var numbers = [20, 19, 7, 20]

hasAnyMatches(numbers, lessThanTen)

If you could explain a little more of what exactly is going on here it would be much appreciated. I ask most of the question in the comments so it's easier to read but the main thing confusing me is condition: Int -> Bool as a parameter.

Upvotes: 2

Views: 1355

Answers (2)

sketchyTech
sketchyTech

Reputation: 5906

As it states in the book, the second argument is a function (what's actually going on I've explained in code comments)

  // 'condition: Int -> Bool' is saying that it accepts a function that takes an Int and returns a Bool
func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool {

    // Takes each item in array in turn
    for item in list {

        // Here each 'item' in the list is sent to the lessThanTen function to test whether the item is less than 10 and returns true if it is the case and executes the code, which in turn returns true 
        if condition(item) {
            return true
        }
    }

    return false
}


// This function is sent as the second argument and then called from hasAnyMatches
func lessThanTen(number: Int) -> Bool {
    return number < 10
}

var numbers = [20, 19, 7, 20]

hasAnyMatches(numbers, lessThanTen)

In the scenario provided, the loop will continue to run until it hits 7, at which point true will be returned. If there was no number beneath 10 then the function would return false.

Upvotes: 4

Jack
Jack

Reputation: 16855

condition: Int -> Bool is the syntax for you to pass in a closure, more commonly known as functions.

The function lessThanTen has a type of Int -> Bool, as can be seen from its signature

inputTypes->outputType is basically all you need to define a function!

It should work like this as well:

hasAnyMatches(numbers, { number in ; return number < 10 } )

// Or like this, with trailing closure syntax
hasAnyMatches(numbers) {
    number in
    return number < 10
}

Upvotes: 1

Related Questions