0

I'm trying to extend the array class writing a simple function that will receive a function as parameter and will use that to filter the current array.

In this example "self" is actually an array.

this is what I used so far:

    func applyFilter(filterFunction: (String) -> Bool) {
    self.filter(filterFunction)
    }

But I'm receiving this error from xCode:

cannot convert value of type '(String) -> BOOL' to expected argument type '_ ' -> Bool

Any ideas?

2
  • please, provide us with implementation of filter function Commented Mar 14, 2018 at 8:43
  • I'm extending the array class. So the filter function is the default array function. Commented Mar 14, 2018 at 8:48

1 Answer 1

3

The error message means that, the generic Array.filter(_:) function is expecting the Array.Element to be passed not a string.

If you change the extension and function to be:

extension Array where Element == String {

    func applyFilter(_ filter: (String) -> Bool) {
        self.filter(filter)
    }

}

As this specifies that the function will only be dealing with String elements then you can pass a function to the closure as such:

func filter(_ value: String) -> Bool { 
    /* Filter how you need */ 
}

["Hello", "World"].applyFilter(filter(_:))
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, I was extending the array of a specific type while trying to filter for another type. Thanks a ton man.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.