David Seek David Seek - 2 months ago 8
iOS Question

Swift / Populate UITableView with Array.count of elements matching certain condition

Currently I'm populating my UITableView by:

var eventDates: [NSMutableDictionary] = []

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

return eventDates.count
}


Every
eventDate
within
eventDates
has a
valueForKey("monthsYear")
.

Hardcoded I want now
eventDates.count
only return the eventDates with the
valueForKey("monthsYear") == "September 2016"
.

In other words, to explain it one more time:

eventDates.count
= 10. But only 5 of them match the condition
valueForKey("monthsYear") == "September 2016"
.

How do I get only those 5 elements to populate the
UITableView
(with only 5 rows).

In theory something like this:

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

let returnValue = 0
for date in eventDates where date.valueForKey("monthsYear") == "September 2016" {
returnValue++
}
return returnValue
}


Help is very appreciated.

Answer

So what you need to do is a simple Filter

let sepDates = eventDates.filter() { $0.valueForKey("monthYear") == "September 2016" }
return sepDates.count

some not answer related stuff stuff

One Advice, try to use models to avoid using valueForKey, so you array would look like

var eventDates: [EventDate] = []

good luck and have fun ;)