2017-05-08 47 views
-2

我有索引超出範圍錯誤,當我從我的數組中刪除對象。有我的代碼。它是一個電梯功能,它採用Floor類的對象,並與此樓層上Passenger類的對象的數組一起工作。我創建了當前樓層對象的臨時副本,然後沿着這個副本排列,如果對象適合條件,我們將此對象推送到Elevator的乘客陣列中,並通過索引從當前樓層對象的原始數組中刪除它。如果這很重要,我使用Equatable協議並創建一個函數進行比較。 感謝您的任何答案。索引超出範圍錯誤,自定義對象數組。 Swift

class Passenger: Equatable{...} 

func ==(l: Passenger, r: Passenger) -> Bool { 
    return l === r 
} 

func checkFloor(f: Floor){ 
    var tempFloor = f 
    var pass = passengers 
    for i in 0..<passengers.count { 
     if(passengers.isEmpty){ 
      break 
     } 
     if(pass[i].getFloor()==f.getIdFloor()){ 
      f.peoples.append(pass[i]) 
      f.peoples[f.peoples.count - 1].setDirection(who: "nothing") 
      //if var index = passengers.index(of: pass[i]) { 
      if let index = searchInArray(who: passengers, who: pass[i]) { 
       passengers.remove(at: index) 
      } 
     } 
    } 
    // in this part I have a problem 
    for i in 0..<tempFloor.countOf() { 
     if(f.peoples.isEmpty || passengers.count >= capacity){ 
      break 
     } 
     if(tempFloor.peoples[i].getDirection()==tempFloor.peoplesDirection() 
     ){ 
      passengers.append(tempFloor.peoples[i]) 
      if let index = f.peoples.index(of: tempFloor.peoples[i]) { 
        if (index >= 0 && index < f.peoples.count) { 
         //print(index) 
         f.peoples.remove(at: index) // index out of range error 
        } 
      } 
     } 
    } 
} 
+0

tempFloor.countOf()是相同的,如果我寫tempFloor.peoples.count –

回答

3

您要刪除的項目,同時列舉了一系列的,所以範圍變化(可能經常出現),但是這不會更新for i in 0..<tempFloor.countOf()

當你從數組刪除項目,每個項目後,該指數改變其指數和計數減少。所以如果你打算這樣做,通常最好是向後枚舉數組,所以刪除當前項目不會影響你下一步做什麼。

爲了演示,試試這個代碼在操場

var arr = [1,2,3,4,5,6,7,8,9,10] 

for (index, item) in arr.enumerated().reversed() { 
    if item % 2 == 0 { 
     arr.remove(at: index) 
    } 
} 

print(arr) 

它將遍歷數組中的項目向後並刪除任何均勻,並且將輸出:

「[1 ,3,5,7,9] \ n「

+0

感謝你很多 –