SwiftUI如何从ReversedCollection消息集合中获取指定ID的对应元素
实现方案
你当前写法的问题在于,@DocumentID是Firebase提供的属性包装器,仅可用于Codable结构体的属性声明场景,不能直接作为集合的查询语法使用,你可以通过first(where:)高阶方法匹配消息id来获取目标消息:
func checkRead(from: String, messages: ReversedCollection<[Message_M]>, ID: String) { // 匹配id找到目标消息,未找到直接返回 guard let targetMsg = messages.first(where: { $0.id == ID }) else { return } if currentUserID != targetMsg.userFrom { // 原有业务逻辑 } }
如果你想要实现类似你预期的简洁调用效果,可以给ReversedCollection加针对性扩展:
// 仅当反转集合元素为Message_M时生效 extension ReversedCollection where Element == Message_M { subscript(messageId: String) -> Message_M? { first(where: { $0.id == messageId }) } }
添加扩展后你就可以直接用如下语法调用:
if currentUserID != messages[ID]?.userFrom { // 业务逻辑 }
优化建议
如果你的消息数量较多、需要频繁通过ID查找消息,建议提前把消息集合转为以ID为key的字典,将查找时间复杂度从O(n)降到O(1):
// 生成字典,重复ID保留第一条数据 let msgDict = Dictionary(messages.map { ($0.id ?? "", $0) }, uniquingKeysWith: { old, _ in old }) // 直接通过ID取值 let targetUserFrom = msgDict[ID]?.userFrom
内容的提问来源于stack exchange,提问作者Flincorp
相关产品推荐
相关产品推荐

