在两个对象数组之间过滤,避免嵌套 for 循环

1 arrays for-loop filtering swift

在 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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这按预期工作(foundList 包含 local[0])但感觉应该有一种“更快速”的方法来做到这一点?

pac*_*ion 5

for循环可以用一个for循环 +where条件重写:

for m in local where server.contains(where: { $0.id == m.id }) {
    foundList.append(m)
}
Run Code Online (Sandbox Code Playgroud)

或结合filter使用contains

foundList = local.filter { m in server.contains(where: { $0.id == m.id }) }
Run Code Online (Sandbox Code Playgroud)

PS另外,使Message结构符合Equatable协议。它允许您简化contains方法:

for m in local where server.contains(m) {
    foundList.append(m)
}
Run Code Online (Sandbox Code Playgroud)

使用filter

foundList = local.filter { server.contains($0) }
Run Code Online (Sandbox Code Playgroud)