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

标签 arrays swift for-loop filtering

在 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)
}

或将 filtercontains 组合:

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/

相关文章:

c++ - 有什么理由不能将堆指针分配给数组吗?

c - 如何在c中重写char数组?

javascript - 搜索数组并返回结果的最佳方法

Python:如何在获得特定输入之前一直重复程序?

c - 从 C 文件中读取测试用例时出错

arrays - Htaccess : multiple parameters and nested parentheses

arrays - 数组未从 For Loop VBA 填充

ios - Swift 属性字符串清除背景文本

ios - UILabel高度计算

ios - AVAudioPlayer 第一次不播放