我正在对元素属性的内容进行测试,以计算出现次数
例如,对于一个简单的字符串数组,当我要使用一种条件进行测试时,此示例可以正常工作:
counts[item.id] = (counts[item.id] ?? 0) + 1
但是我的问题是,如何在不同条件下进行相同的测试,不仅通过测试item.id,例如,我还想对item.email进行测试。是这样吗
counts[item.id] = (counts[item.id] && counts[item.email] = (counts[item.email] ?? 0) + 1
这是我在其中添加键值,键作为对象元素以及值作为出现次数的数组
这是一个清晰的例子
let arr = [Student, Student, Student, Student]
var counts: [String: Int] = [:]
for item in arr {
counts[item.id] = (counts[item.id] ?? 0) + 1
}
for (key, value) in counts {
print("\(key) occurs \(value) time(s)")
}
output:
44442 occurs 1 time(s)
34434 occurs 1 time(s)
22222 occurs 2 time(s)
感谢您的帮助。
答案 0 :(得分:0)
答案很简单,它是在我的课程的扩展中,并通过添加Equatable,
extension notificationManager: Equatable {
static func ==(lhs: notificationManager, rhs: notificationManager) -> Bool {
return lhs.fromwho.username == rhs.fromwho.username && lhs.forwho.username == rhs.forwho.username && lhs.activity.objectId == rhs.activity.objectId
}}
然后我只添加计数
for item in orignalNotifs {
notificationManager.Notifcounts[item] = (notificationManager.Notifcounts[item] ?? 0) + 1
}