Ios 如何比较两个数组对象-Swift 4
我有两个类型为Ios 如何比较两个数组对象-Swift 4,ios,arrays,swift,enumerate,Ios,Arrays,Swift,Enumerate,我有两个类型为[Any]-字典对象的数组 而其他数组包含其他对象集[Any](第二个数组对象包含在第一个数组中) 我需要找到第二个数组元素的第一个数组的索引 例如: let firstArray = [["key1":6],["key2":8],["key3":64],["key4":68],["key5":26],["key6":76]] let secondArray = [["key3":64],["key6":68]] 如何找到secondArray元素的firstArray索引 l
[Any]
-字典对象的数组而其他数组包含其他对象集
[Any]
(第二个数组对象包含在第一个数组中)
我需要找到第二个数组元素的第一个数组的索引
例如:
let firstArray = [["key1":6],["key2":8],["key3":64],["key4":68],["key5":26],["key6":76]]
let secondArray = [["key3":64],["key6":68]]
如何找到secondArray
元素的firstArray
索引
let index = firstArray.index{$0 == secondArray[0]};
print("this value ", index);
将打印可选(2),它基本上是2
将打印可选的(2),基本上是2个首先,您从
第二个数组中获取键。然后,尝试在firstArray
中查找键的索引。请注意,如果键不存在,则某些值可能为零
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]
我还添加了一个示例,结果为零。首先,从第二个数组中获取键。然后,尝试在firstArray
中查找键的索引。请注意,如果键不存在,则某些值可能为零
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]
我还添加了一个示例,其中结果为nil。最好使用该方法的Array.index(where:)
,这样可以清楚地知道您在做什么。使用尾随闭包语法会使读者很难知道您在做什么。最好使用该方法的Array.index(where:)
,以便清楚地知道您在做什么。使用尾随闭包语法让读者很难知道你在做什么。你是说你想把整个第二个数组作为第一个数组的子数组来查找吗?你的问题不是clear@DuncanC:没错。第二个数组元素包含在第一个数组中。您是说要将整个第二个数组作为第一个数组的子数组来查找吗?你的问题不是clear@DuncanC:没错。第二个数组元素包含在第一个数组元素中。