Follow up to event sorting

This is a short follow up article regarding the problems I described in this post.

I spent some time mocking this up in a Swift Playground on my iPad. First I added a new container object called EventContainer. This is an object that I can map my events to, while keeping a reference to the Core Data Event record.

class EventContainer {
    enum EventType {
        case startEvent
        case endEvent
    var date: Date
    var eventType: EventType
    var event: Event
    init(date: Date, eventType: EventType, event: Event) { = date
        self.eventType = eventType
        self.event = event

I started by mapping the entire list of fetched events to an array of EventContainer

let startDateRows: [EventContainer] = fetchResults.compactMap ( { EventContainer(date: $0.dateStart!, eventType: .startEvent, event: $0 )} )

Next I filtered the fetched events to just those with end date data

let endDataData = fetchResults.filter({$0.includeEndDate == true && $0.dateEnd != nil})
let endDateRows: [EventContainer] = endDataData.compactMap( { EventContainer(date: $0.dateEnd!, eventType: .endEvent, event: $0 ) } )

Lastly I combined these arrays into one new array and sorted it based on the date property from the EventContainer

let fullList = startDateRows + endDateRows
fullList.sorted(by: {
    $$ == .orderedDescending

Now I have a sorted array of EventContainers that I can use to build my list UI. Each list row can still access the Core Data Event entity to pass on to editing views. I think this is a reasonable approach, but I’m really just guessing. If you know a better way to do this please get in touch using the contact form or contact me on Twitter.