我有一个简单的见面会
class Meetup {
var title: String
var date: String
}
从meetup.com获取的一系列见面聚会称为
meetups
。我想按日期在字典中组织这些见面会:
[String, [Meetup]]
其中字符串是日期。这是我的实现
func buildDateMeetupDict(meetups: [Meetup]) -> [String, [Meetup]] {
var dateMeetupDict = [String: [Meetup]]()
for meetup in meetups {
for var meetupsByDay in dateMeetupDict {
if meetupsByDay.day == meetup.day {
meetupsByDay.meetupArray.append(meetup)
} else {
let newMeetupDay = [meetup.day, [meetup]]
dateMeetupDict.append(newMeetupDay)
}
}
}
return dateMeetupDict
}
它可以工作,但效率极低,而且感觉和外观都一样贫民窟。
如何有效地从数组中的对象中提取属性并基于该属性构建索引?
最佳答案
我几乎会像您正在做的那样做。毕竟,您只循环一次遍历数组。
我认为您可能想更清楚地表达算法。每次聚会的选择是:
如果该键不存在,则创建它并使其值成为其中包含此Meetup的数组;
如果键确实存在,请将此聚会添加到其值数组中。
我认为我们可以很明确地说如下:
// here's a test class
// [Note: I used `id` instead of `date`, but it's still just a string...]
class Meetup : CustomStringConvertible {
var id: String
var title: String
init(id:String, title:String) {
self.id = id; self.title = title
}
var description: String {
return "\(self.id)/\(self.title)"
}
}
// here's a test array of Meetups
let meetups : [Meetup] = [
Meetup(id:"one", title:"Howdy"),
Meetup(id:"two", title:"Hello"),
Meetup(id:"two", title:"Bonjour"),
Meetup(id:"one", title:"Namaste")
]
// and here's our actual code!
var dict = [String:[Meetup]]()
for meetup in meetups {
let val = dict[meetup.id]
dict[meetup.id] = val == nil ? [meetup] : val! + [meetup]
}
现在让我们证明它是可行的:
print(dict) // ["one": [one/Howdy, one/Namaste], "two": [two/Hello, two/Bonjour]]
因此,我们最后得到了一个词典,该词典的键是原始的
id
(您的日期),并且每个id
的值都是具有该id
的Meetups的数组。