我有索引超出範圍錯誤,當我從我的數組中刪除對象。有我的代碼。它是一個電梯功能,它採用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 –