简体   繁体   English

如何正确获得一套EKCalendars

[英]How to get a set of EKCalendars properly

I now develop an iOS App that shows a list of iCloud EKCalendars. 我现在开发一个iOS应用程序,其中显示iCloud EKCalendars的列表。 My swift codes can get a set of iCloud EKCalendars, but the order is always different. 我的快捷代码可以获取一组iCloud EKCalendar,但是顺序总是不同的。 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

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. 因此, let calendars = source.calendars(for: .event)的类型为Set<EKCalendar> ,根据定义, Set是一种无序的数据类型,因此,每当您遍历set时,它始终可能处于不同的顺序,唯一的原因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 . 如果要订购日历,则必须自己订购,一种是按titlecalendarIdentifier订购。

Just sort the Set , the result is an ordered array: 只需sort Set sort ,结果是一个有序数组:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM