我有一个数组VIPArray
和AddressArray
,因此我想根据AddressArray
过滤VIPArray
。我怎么能这样做?
VIPArray
看起来像这样
let VIPArray = [["name": "John B"], ["name": "Sara K"]]
AddressArray
看起来像这样
let AddressArray = [Address(name: "John B", imageURL: "johnb", address: "178 Main St."),
Address(name: "Dave H", imageURL: "daveh", address: "1011 Victoria St.."),
Address(name: "Sara K", imageURL: "sarak", address: "279 Maple Av."),
Address(name: "Niles K", imageURL: "nilesk", address: "45 King St."),
Address(name: "Ingrid G", imageURL: "ingridg", address: "33 Union St.")
所以我想得到这个结果:(过滤的AddressArray)
[
Address(name: "John B", imageURL: "johnb", address: "178 Main St."),
Address(name: "Sara K", imageURL: "sarak", address: "279 Maple Av.")
]
答案 0 :(得分:0)
1。您只需使用for-in loop
和filter
即可获得预期值:
for VIP in VIPArray
{
let result = AddressArray.filter({ $0.name == VIP["name"] })
print(result)
}
2. 或者,您可以使用map
和filter
的组合来获取预期值。
let result = VIPArray.map { (VIP) -> Address? in
if let address = AddressArray.filter({ $0.name == VIP["name"] }).first
{
return address
}
return nil
}
print(result)
如果您仍然遇到任何问题,请告诉我。
答案 1 :(得分:0)
struct Address {
var name: String
var imageURL: String
var address: String
}
let VIPArray = [["name": "John B"], ["name": "Sara K"]]
let AddressArray = [Address(name: "John B", imageURL: "johnb", address: "178 Main St."),
Address(name: "Dave H", imageURL: "daveh", address: "1011 Victoria St.."),
Address(name: "Sara K", imageURL: "sarak", address: "279 Maple Av."),
Address(name: "Niles K", imageURL: "nilesk", address: "45 King St."),
Address(name: "Ingrid G", imageURL: "ingridg", address: "33 Union St.")]
var filtered = [Address]()
for element in VIPArray {
for address in AddressArray {
if element["name"] == address.name {
filtered.append(address)
}
}
}
for record in filtered {
print(record)
}
输出:
地址(姓名:“John B”,imageURL:“johnb”,地址:“178 Main St。”)
地址(姓名:“Sara K”,imageURL:“sarak”,地址:“279 Maple Av。”)
或者:
let filtered: [Address] = AddressArray.filter { (address) -> Bool in
for vip in VIPArray {
if vip["name"] == address.name {
return true
}
}
return false
}
答案 2 :(得分:0)
let VIPArray = [["name": "John B"], ["name": "Sara K"]]
struct Address {
let name: String
let imageURL: String
let address: String
}
let addressArray = [Address(name: "John B", imageURL: "johnb", address: "178 Main St."),
Address(name: "Dave H", imageURL: "daveh", address: "1011 Victoria St.."),
Address(name: "Sara K", imageURL: "sarak", address: "279 Maple Av."),
Address(name: "Niles K", imageURL: "nilesk", address: "45 King St."),
Address(name: "Ingrid G", imageURL: "ingridg", address: "33 Union St.")]
let myVips = addressArray.filter() {VIPArray.contains(["name":$0.name])}