我正在尝试比较两个数组(array1, array2)
,如果array2
中包含特定的键值,则array1
中包含array2值的键值需要打印出来它的索引路径'。
我几乎可以使用的代码,应用程序崩溃,因为在通过键时,array2超出范围,因为它包含的数组少于array1
如果其他数组较小,如何让代码查找匹配?
let array1 = [["aaa","bbb","ccc","ddd","eee"], ["fff","ggg","hhh","matched","iii"], ["lll","mmm","nnn","ooo","ppp"], ["666","777","888","999","000"] ] //4 elements
let countArray1 = array1.enumerate()
let array2 = [["111","222"], ["333","444"], ["matched","555"]] // 3 elements
for (index, element) in countArray1{
let containedValue = array1[index].contains(array2[index][0])
if (containedValue) == true{
print("The index of the contained value is: ????") //error
}
}
答案 0 :(得分:0)
我会将较小的2D数组转换为1D数组,然后遍历较大数组的两个维度并使用NSArray.contains:
免责声明:此代码未经测试。 @Community:如果您偶然发现并发现错误或可以更好地编写,评论或编辑的内容。我比Swift更多地使用Obj-C。
//convert 2D array to 1D
func from2Dto1D(array: NSArray) -> NSArray {
var newArr = NSMutableArray()
for (d1) in array {
for (d2) in d1 {
newArr.append(d2)
}
}
return newArr as NSArray
}
func hasMatch(array1: NSArray, array2: NSArray) -> boolean {
var bigger: NSArray
var smaller: NSArray
if (array1.count > array2.count){
bigger = array1
smaller = from2Dto1D(array2)
}else{
bigger = array2
smaller = from2Dto1D(array1)
}
for (d1) in bigger{
for (item) in d1 {
if (smaller.contains(item)){
print("Match found");
return true
}
}
}
return false
}
答案 1 :(得分:0)
您可以展平两个数组,然后枚举它们以检查对象匹配的索引。
$mdGestureProvider.skipClickHijack();