我有一个简单的聚会课
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
}
它有效,但效率极低,感觉和看起来同样贫民窟。
如何从数组中的对象中提取属性并有效地基于该属性构建索引?
答案 0 :(得分:1)
我会像你一样做到这一点。毕竟,你只是通过数组循环。
我想你可能想要更清楚地表达算法。您对每次聚会的选择是:
如果密钥不存在,请创建它并使其值为包含此Meetup的数组;
如果密钥确实存在,请将此meetup附加到其value数组。
我认为我们可以非常清楚地说明如下:
// 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
s(您的日期),每个id
的值是与id
的Meetup数组