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
例如,如果arrID
=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数组。