在 Swift 4 中,如何将仅检查一个属性是否相等的嵌套 for 循环转换为过滤器?
基本示例:
// Basic object
struct Message {
let id: String
let content: String
init(id: String, content: String) {
self.id = id
self.content = content
}
}
// Array of objects
let local = [Message.init(id: "1234", content: "test1"), Message.init(id: "2345", content: "test2")]
// Array of objects, one has updated content
let server = [Message.init(id: "1234", content: "testDiff1"), Message.init(id: "3456", content: "test3")]
var foundList = [Message]()
// Nested loop to find based on one property matching
for i in local {
for j in server {
if i.id == j.id {
foundList.append(i)
}
}
}
这按预期工作(foundList 包含 local[0]),但感觉应该有一种“更快速”的方法来做到这一点?
最佳答案
for
循环可以用一个 for
循环 + where
条件重写:
for m in local where server.contains(where: { $0.id == m.id }) {
foundList.append(m)
}
或将 filter
与 contains
组合:
foundList = local.filter { m in server.contains(where: { $0.id == m.id }) }
附言此外,使 Message
结构符合 Equatable
协议(protocol)。它允许您简化 contains
方法:
for m in local where server.contains(m) {
foundList.append(m)
}
使用过滤器
:
foundList = local.filter { server.contains($0) }
关于arrays - 在两个对象数组之间过滤,避免嵌套 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50132278/