shuvroche
shuvroche

Reputation: 11

How to get a set of EKCalendars properly

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

Upvotes: 1

Views: 897

Answers (2)

vadian
vadian

Reputation: 285079

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) }
}

Upvotes: 1

Ladislav
Ladislav

Reputation: 7283

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.

Upvotes: 2

Related Questions