从元组数组中删除元组

时间:2017-11-08 15:42:16

标签: arrays swift tuples

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继续减少,迭代器我继续增加,直到错误发生“致命索引超出范围”

我的目标是从元组数组中删除一个元组,如果它的值不符合标准。

我也尝试过类似的事情:

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)
   }
}

1 个答案:

答案 0 :(得分:1)

当前问题是您需要反向迭代以避免&#34;索引超出范围&#34;问题。

更简单的解决方案是在阵列上使用Diff = CAST(CASE WHEN X.Diff = 0 THEN NULL ELSE X.Diff END AS VARCHAR(10)) + ' days' + ' (' + CAST(1 AS VARCHAR(2)) + '-' + CAST(X.Id AS VARCHAR(2)) + ')' 。然后整个filter循环可以替换为:

for