struct Human{
let name: String
let id: String
let travelled: String
}
struct Animal {
let name: String
let id: String
let travelled: String
}
// Consider no human and animal object can have same name
let human1 = Human(name: "vikas", id: "12", travelled: "123")
let human2 = Human(name: "jacky", id: "15", travelled: "343")
let human3 = Human(name: "lucy", id: "32", travelled: "132")
let animal1 = Animal(name: "jacky", id: "56", travelled: "8979")
let animal2 = Animal(name: "lucy", id: "78", travelled: "678")
let animal3 = Animal(name: "jimmy", id: "98", travelled: "690")
let humans = [human1, human2, human3]
let animals = [animal1, animal2, animal3]
var list = [[String: String]]()
// can we eleminate this for loop with filter or something else
for human in humans {
if let animal = animals.first(where: {$0.name == human.name}){
let data = ["humanId": human.id, "animalId": animal.id]
list.append(data)
}
}
print(list)
输出:
[["humanId": "15", "animalId": "56"], ["humanId": "32", "animalId": "78"]]
有没有一种方法我们可以一次应用多个过滤器以获得所需的输出 找不到或创建一个
答案 0 :(得分:1)
您可以尝试改用 compactMap(_:)
。
let list = humans.compactMap { (human) -> [String:String]? in
if let animal = animals.first(where: { $0.name == human.name }) {
return ["humanId": human.id, "animalId": animal.id]
}
return nil
}
答案 1 :(得分:1)
此解决方案仍使用循环,但如果存在则将找到多个匹配项
animals.forEach {animal in
let filtered = humans.filter { $0.name == animal.name }
.map { human -> [String: String] in ["humanId": human.id, "animalId": animal.id] }
list.append(contentsOf: filtered)
}
答案 2 :(得分:-1)
在这里
for index in 0..<humans.count {
list[index]["humanId"] = humans[index]
list[index]["animalId"] = animals[index]
}