【发布时间】:2018-10-12 10:10:26
【问题描述】:
在 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 包含本地 [0]),但感觉应该有一种“更快捷”的方式来做到这一点?
【问题讨论】:
标签: arrays swift for-loop filtering