gpt4 book ai didi

ios - 如何计算具有不同条件的 Swift 对象数组中某个元素的出现次数

转载 作者:行者123 更新时间:2023-11-30 10:56:23 25 4
gpt4 key购买 nike

我正在对元素属性的内容进行测试,以便计算出现次数

例如,对于一个简单的字符串数组,当我想用​​一个条件进行测试时,这个示例就可以正常工作:

    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)

感谢您的帮助。

最佳答案

答案非常简单,它是在我的类的扩展中并添加 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
}

关于ios - 如何计算具有不同条件的 Swift 对象数组中某个元素的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53911002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com