Ios 使用数组值筛选字典

Ios 使用数组值筛选字典,ios,arrays,filtering,Ios,Arrays,Filtering,我有一个数组,它包含像 var ID = ["782", "783", "784", "785", "786", "788", "789", "790", "791", "792", "793", "795", "805"] 还有一本字典一样的书 Var arr2 = [["ID":"782","AmenitiesURL":"xyx.com"],["ID":"783","AmenitiesURL":"xybx.com"],["ID":"784","AmenitiesURL":"xyax.com

我有一个数组,它包含像

var ID = ["782", "783", "784", "785", "786", "788", "789", "790", "791", "792", "793", "795", "805"]
还有一本字典一样的书

Var arr2 = [["ID":"782","AmenitiesURL":"xyx.com"],["ID":"783","AmenitiesURL":"xybx.com"],["ID":"784","AmenitiesURL":"xyax.com"]]
在图像中也可以看到。现在我想获取ID的url

例如,如果arr
ID
=
784
那么我想在
arr2
中找到该
ID
,并获取它们的
url
并附加到新数组中

简而言之,两个数组一个用于
ID
,另一个用于
URL


您可以使用以下方法实现这一点:

let urls = ID.compactMap { (id) in
    return arr2.first(where: {$0["ID"] == id})?["AmenitiesURL"]
}
输出:

print(urls) //["xyx.com", "xybx.com", "xyax.com"]

对于
ID数组
中的所有ID,您将从
arr2数组
中获得
修正URL
值。您可以使用以下方法获得该值:

let urls = ID.compactMap { (id) in
    return arr2.first(where: {$0["ID"] == id})?["AmenitiesURL"]
}
输出:

print(urls) //["xyx.com", "xybx.com", "xyax.com"]

对于
ID数组
中的所有ID,您将从
arr2数组

中获得
修正URL
值,以获取特定ID的URL

let id = "784"
if let dict = arr2.first(where: { $0["ID", default:""] == id }), let urlString = dict["AmenitiesURL"] {
    print(urlString)
}

获取特定id的URL

let id = "784"
if let dict = arr2.first(where: { $0["ID", default:""] == id }), let urlString = dict["AmenitiesURL"] {
    print(urlString)
}

另一种方法。虽然这个保留了arr2的结构

let filteredArray = arr2.filter { dict -> Bool in
    for id in ID{
        if dict["ID"] == id{
            return true
        }
    }
    return false
}

另一种方法。虽然这个保留了arr2的结构

let filteredArray = arr2.filter { dict -> Bool in
    for id in ID{
        if dict["ID"] == id{
            return true
        }
    }
    return false
}

将字典数组更改为结构数组。在我看来,一开始就不应该使用dict数组。请将dictionary数组更改为struct数组。在我看来,你根本不应该拥有dict数组。