Swift 3 filter array by date

I have a core data array of objects that I would like to filter by a user selected date. I'm trying to use the .filter function but I'm getting an error


The current filter code is:

let filteredItems = items.filter( { _ in return item.completeDate == date } )


The comparison date is pulled from higher up the chain and the completeDate is the core data attribute.

I have checked both outputs and they will match - I just can't seem to get the final filter part down.


Thanks

Answered by goldsdad in 203829022

The underscore for the parameter name is telling the closure to ignore the argument (each element of an array in this case) passed to it. Try it with a parameter named `item`:


let filteredItems = items.filter { item in return item.completeDate == date }


Or more concisely:


let filteredItems = items.filter { $0.completeDate == date }


See the Swift Programming Language ebook (also in Xcode documentation) for info about closure syntax.

Accepted Answer

The underscore for the parameter name is telling the closure to ignore the argument (each element of an array in this case) passed to it. Try it with a parameter named `item`:


let filteredItems = items.filter { item in return item.completeDate == date }


Or more concisely:


let filteredItems = items.filter { $0.completeDate == date }


See the Swift Programming Language ebook (also in Xcode documentation) for info about closure syntax.

Swift 3 filter array by date
 
 
Q