2017-05-08 79 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

感谢你很多 –