Func 查看两个数组是否具有相同的值:
func hasAllSame(largeCombinedArry:[Int], wantToKeep: [Int])->Bool{
var howManySame = [Int]()
for intElement in largeCombinedArry{
if wantToKeep.contains(intElement){
howManySame.append(intElement)
}
}
howManySame.sort()
if wantToKeep == howManySame{
print("These are the same!")
return true
}
else{
print("These are NOT same!")
return false
}
}
元组数组声明如下:
var TuplesArry:[(score: Double, value: [Int])] = []
这样填充的数组:
for (arry1, score) in zip(arryOfArrays, AllScores) {
let calculatedDiff = otherValue - score
TuplesArry.append((score: calculatedDiff, value: arry1))
}
var arrayForComparison = [8,9,7,6]
arrayForComparison.sort()
在函数调用 hasAllSame() 多次迭代后,此处发生错误
for i in 0..<TuplesArry.count{
if hasAllSame(largeCombinedArry: TuplesArry[i].value, wantToKeep:
arrayForComparison){
//do nothing
}
else{
/*
want to remove tuple that does not have all elements that are
in arrayForComparison
*/
TuplesArry.remove(at: i)
}
}
这段代码似乎正在工作,但似乎 tuplesArry.count 继续减少,迭代器 i 继续增加,直到发生错误“致命索引超出范围”
我的目标是从元组数组中删除一个元组,如果它的值不符合标准。
我也试过类似的东西:
for tuple in TuplesArry{
if hasAllSame(largeCombinedArry: tuple.value, wantToKeep:
arrayForComparison){
//do nothing
}
else{
//this does NOT work
let index = TuplesArry.index(of:tuple)
TuplesArry.remove(at: index)
}
}
当前的问题是您需要反向迭代以避免“索引超出范围”问题。
更简单的解决方案是filter
在您的阵列上使用。然后你整个for
循环可以替换为:
TouplesArry = TouplesArry.filter { hasAllSame(largeCombinedArry: $0.value, wantToKeep: arrayForComparison) }
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句