快速比较两个结构的值 [英] Compare value from two struct in swift
本文介绍了快速比较两个结构的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个结构体和两个与之对应的数组,我正在尝试比较两个数组值并将其打印在一个过滤数组中结构体并获得一个数组
I have two struct and two arrays corresponding to it and I am trying to compare the two array values and print it in one filtered array i did try and use filter but its giving me an error I want to compare an id from both the struct and get one single array
构造一个
struct One {
let ID: String
let name: String
let lastName: String
}
阵列一
var oneData = [One]()
oneData = [One(ID: "1", name: "hello1", lastName: "last2"), One(ID: "1", name: "hello2", lastName: "last2"), One(ID: "2", name: "hello3", lastName: "last3"), One(ID: "3", name: "hello4", lastName: "last4")]
结构二
struct Two {
let ID: String
let name2: String
let lastName2: String
}
数组二
var twoData = [Two]()
twoData = [Two(ID: "1", name2: "hello1", lastName2: "last1"), Two(ID: "2", name2: "hello2", lastName2: "last2"), Two(ID: "3", name2: "hello3", lastName2: "last3"), Two(ID: "4", name2: "hello4", lastName2: "last4"), Two(ID: "5", name2: "hello5", lastName2: "last5")]
我的过滤数组
var mainArray = [Two]()
我用来过滤的代码,这给了我一个错误
mainArray = oneData.filter{ $0.ID == twoData.contains(where: $0.ID)}
推荐答案
获取数组oneData
的ID
与ID
匹配的对象数组 twoData
中的任何对象.您可以执行以下操作:
To get objects of array oneData
whose ID
matched with ID
of any object from array twoData
. You can do following:
// Array One
var oneData = [One]()
oneData = [One(ID: "1", name: "hello1", lastName: "last2"),
One(ID: "1", name: "hello2", lastName: "last2"),
One(ID: "2", name: "hello3", lastName: "last3"),
One(ID: "3", name: "hello4", lastName: "last4")]
// Array Two
var twoData = [Two]()
twoData = [Two(ID: "1", name2: "hello1", lastName2: "last1"),
Two(ID: "2", name2: "hello2", lastName2: "last2"),
Two(ID: "3", name2: "hello3", lastName2: "last3"),
Two(ID: "4", name2: "hello4", lastName2: "last4"),
Two(ID: "5", name2: "hello5", lastName2: "last5")]
let mainArray = oneData.filter { i in twoData.contains{ i.ID == $0.ID } }
print(mainArray)
这篇关于快速比较两个结构的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文