检查字典数组的值是否与数组元素列表匹配

时间:2016-04-13 11:07:32

标签: arrays swift dictionary predicate

我在Swift中有一个数组(items)和一组字典(数据):

let items = [2, 6, 4]

var data = [
    ["id": "1", "title": "Leslie", "color": "brown"],
    ["id": "8", "title": "Mary", "color": "red"],
    ["id": "6", "title": "Joe", "color": "blue"],
    ["id": "2", "title": "Paul", "color": "gray"],
    ["id": "5", "title": "Stephanie", "color": "pink"],
    ["id": "9", "title": "Steve", "color": "purple"],
    ["id": "3", "title": "Doug", "color": "violet"],
    ["id": "4", "title": "Ken", "color": "white"],
    ["id": "7", "title": "Annie", "color": "black"]
]

我想创建一个包含那些" id"的字典数组的数组。等于'项目中提供的数字'阵列。 Aka我想最终得到一个阵列:

var result = [
    ["id": "6", "title": "Joe", "color": "blue"],
    ["id": "2", "title": "Paul", "color": "gray"],
    ["id": "4", "title": "Ken", "color": "white"]
]

我试图使用谓词,但在经历了严重的头痛和心脏骤停后,我并没有使用它们。对于这项任务来说,他们看起来非常复杂。我现在处于一个我想在一个简单的for-in循环中执行此操作的地方。

使用谓词或其他方法有一种聪明的方法吗?

3 个答案:

答案 0 :(得分:6)

像这样使用size_tstd

filter

答案 1 :(得分:0)

试试这个,应该有效:

let items = [2, 6, 4]
var data = [
    ["id": "1", "title": "Leslie", "color": "brown"],
    ["id": "8", "title": "Mary", "color": "red"],
    ["id": "6", "title": "Joe", "color": "blue"],
    ["id": "2", "title": "Paul", "color": "gray"],
    ["id": "5", "title": "Stephanie", "color": "pink"],
    ["id": "9", "title": "Steve", "color": "purple"],
    ["id": "3", "title": "Doug", "color": "violet"],
    ["id": "4", "title": "Ken", "color": "white"],
    ["id": "7", "title": "Annie", "color": "black"]
]

var result = [Dictionary<String, String>]()

for index in 0..<data.count {
    let myData = data[index]
    let dataID = data[index]["id"]
    for i in 0..<items.count {
        if dataID == "\(items[i])" {
            result.append(myData)
        }
    }
}

for i in 0..<result.count {
    print(result[i])
}

结果是:

enter image description here

答案 2 :(得分:0)

感谢大家的回复!我认为Eric D的解决方案最接近我所追求的目标。

我终于能够在raywenderlich.com上找到具有良好描述的解决方案:https://www.raywenderlich.com/82599/swift-functional-programming-tutorial

使用该方法(再次,非常接近Eric D的建议),首先我可以将其分解为:

func findItems(value: [String: String]) -> Bool {
    return items.contains(Int(value["id"]!)!)
}
var result = data.filter(findItems)

我可以进一步减少:

var result = data.filter {
    (value) in items.contains(Int(value["id"]!)!)
}

再次,可以减少到一行,如:

var result = data.filter { items.contains(Int($0["id"]!)!) }

再次感谢大家!