[英]How do I compare two array Objects - Swift 4
I have 2 Array of type [Any]
- objects of dictionaries 我有2个
[Any]
类型的数组-字典对象
And other array contains other set of objects [Any]
(2nd array objects are contains in first array) 其他数组包含其他对象集
[Any]
(第二个数组对象包含在第一个数组中)
I need to find the index of the first array of second array elements 我需要找到第二个数组元素的第一个数组的索引
eg: - 例如:-
let firstArray = [["key1":6],["key2":8],["key3":64],["key4":68],["key5":26],["key6":76]]
let secondArray = [["key3":64],["key6":68]]
How can I find the firstArray
index of secondArray
elements 我如何找到
secondArray
元素的firstArray
索引
let index = firstArray.index{$0 == secondArray[0]};
print("this value ", index);
will print optional(2) , it is basically 2 将打印optional(2),基本上是2
First, you take the keys from your secondArray
. 首先,从
secondArray
获取密钥 。 Then, you try to find the index of key in your firstArray
. 然后,您尝试在
firstArray
找到键的索引 。 Be aware that some values might be nil if the key doesn't exist. 请注意,如果键不存在,则某些值可能为nil。
let firstArray = [["key1":6],["key2":8],["key3":64],["key4":68],["key5":26],["key6":76]]
let secondArray = [["key3":64],["key6":68], ["key8": 100]]
let indexes = secondArray
.map({ $0.first?.key }) //map the values to the keys
.map({ secondKey -> Int? in
return firstArray.index(where:
{ $0.first?.key == secondKey } //compare the key from your secondArray to the ones in firstArray
)
})
print(indexes) //[Optional(2), Optional(5), nil]
I also added an example case where the result is nil. 我还添加了一个示例案例,结果为零。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.