我有索引超出范围错误,当我从我的数组中删除对象。有我的代码。它是一个电梯功能,它采用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
}
}
}
}
}
tempFloor.countOf()是相同的,如果我写tempFloor.peoples.count –