在我的应用程序中,我有一个对象数组的类:EventObjects',有几个属性,比如'date:NSDate?'和'stuffToDo:String?'从日历数据库中提取的内容。我现在尝试实现的是将所有具有相同日期属性的EventObject放在“class:EventsAtSameDate”的另一个对象中。
class EventsAtSameDate: NSObject
{
var date:NSDate?
var eventObjects:NSArray<EventObject>?
}
最后有一个带有EventsAtSameDate的嵌套数组。
var nestedArrayOfEventsAtSameDateObjects: Array<EventsAtSameDate>?
我知道如何使用.filter .sort .sortInPlace等函数搜索和排序数组。但是,如何将数组中的日期相互比较并将它们放在另一个嵌套数组中呢?
答案 0 :(得分:2)
您可以实例化一个字典,以便在对EventObject
类型的初始数组进行一次迭代时跟踪存在的日期。然后迭代字典以实例化EventsAtSameDate
的类并将它们附加到nestedArrayOfEventsAtSameDateObjects: [EventsAtSameDate]
代码看起来像:
var nestedArrayOfEventsAtSameDateObjects = [EventsAtSameDate]()
//instantiate a dictionary that uses Date as the key and an array of EventObject as the associated value
var dictionary = [Date: [EventObject]]()
//iterate through your intial array of EventObjects
for obj in eObjs {
//check if you have already seen the date in the collection
if dictionary[obj.date] != nil {
//if you have - then append it to that date
dictionary[obj.date]?.append(obj)
continue
}
//otherwise, add it to the dictionary for a check later in the loop
dictionary[obj.date] = [obj]
}
//then iterate through the dictionary
for (date, eObjs) in dictionary {
if eObjs.count > 1 {
let sameDate = EventsAtSameDate()
sameDate.date = date
sameDate.eventObjects = eObjs
nestedArrayOfEventsAtSameDateObjects.append(sameDate)
}
}
答案 1 :(得分:1)
我会按日期对事件数组进行排序,然后迭代它们。检查日期是否比上一个更新,如果是,则创建另一个存储。
class Event {
var date:Date!
}
class EventsList
{
var date:Date!
var events:[Event]!
}
func createEventsLists(sortedEvents: [Event]) -> [EventsList] {
guard sortedEvents.count > 0 else { return [] }
var currentEventList = EventsList()
var result = [currentEventList]
var lastDate = sortedEvents.first!.date
for event in sortedEvents {
let newDate = event.date.compare(lastDate!) != .orderedDescending
if newDate {
currentEventList = EventsList()
result.append(currentEventList)
}
currentEventList.events.append(event)
lastDate = event.date
}
return result
}