How to get a set of EKCalendars properly

866 Views Asked by At

I now develop an iOS App that shows a list of iCloud EKCalendars. My swift codes can get a set of iCloud EKCalendars, but the order is always different. Could anyone give me advice to get the set in order?

let eventStore = EKEventStore()
let sources = eventStore.sources
for source in sources {
    if (source.title == "iCloud") {
        let calendars = source.calendars(for: .event)
        for calendar in calendars {
            print("calendar title = " + calendar.title)
        }
    }
}

Example of the result of the codes:

calendar title = title1
calendar title = title6
calendar title = title5
calendar title = title3
calendar title = title4
calendar title = title2
2

There are 2 best solutions below

5
Ladislav On

So let calendars = source.calendars(for: .event) is of type Set<EKCalendar>, by definition a Set is data type that is not ordered so whenever you iterate through a set it could always be in different order, the only thing that Set enforces is that there is only one instance of the object it the set.

If you want to have calendars ordered you will have to order it by yourself, one is to order them by title or calendarIdentifier.

4
vadian On

Just sort the Set, the result is an ordered array:

let eventStore = EKEventStore()
let sources = eventStore.sources.filter{ $0.title == "iCloud" }
for source in sources {
    let calendars = source.calendars(for: .event).sorted{ $0.title < $1.title }
    calendars.forEach { print("calendar title = ", $0.title) }
}