Mike_NotGuilty Mike_NotGuilty - 1 month ago 39x
iOS Question

Swift - Display array of custom objects with sections sorted by date in UITableView

I have a array full of custom Event objects.
Every event has a

Right now I display every event in one big section.
But what I want is that all events should be ordered by the date and every date should has its own section header.

What's the best and fastest way to sort all the objects into the different sections.

I thought about creating a main array with sub-arrays. Each sub-array is one date so that I can access the different sections like this
let section = bigarray[0]

But is this really the best and fastest way to do this task?


First you can create a Array<NSDate> to hold all dates. and then create a Dictionary<NSDate, Array<Event>>, In this Dictionary you can group events in to corresponding Array. At last use Array<NSDate> to get sections, in section you can get corresponding Array<Event> through query key.

class Event: NSObject {
  var date: NSDate?

var events: Array<Event> = Array()

for i in 1...100 {
  let event: Event = Event()
  event.date = NSDate.init(timeIntervalSinceNow: Double(i*86400/2))

var dates: Array<NSDate> = Array()


for event in events {
  var sameDay: Bool = false
  for date in dates {
    if NSCalendar.currentCalendar().isDate(date, inSameDayAsDate:event.date!) {
      sameDay = true
  if !sameDay {

var grouped: Dictionary<NSDate, Array<Event>> = Dictionary()

for date in dates {
  var dateEvents: Array<Event> = Array()
  for event in events {
    if NSCalendar.currentCalendar().isDate(event.date!, inSameDayAsDate: date) {
  grouped[date] = dateEvents