2017-08-13 43 views
1

我有殭屍的陣列在結構的數組的索引,每個殭屍是一個結構如下:查找根據1個部件SWIFT

struct Zombie { 
    var number: Int 
    var location : Int 
    var health : Int 
    var uid : String 
    var group: Int 
} 

我有殭屍的陣列

ZombieArray = [Zombie1, Zombie2, Zombie3] 

我必須在更新時更新zombieHealth,但我需要找到它是第一個殭屍。每個殭屍的位置,號碼和UID都是唯一的,因此可以搜索任何殭屍。這是我嘗試和得到了一個錯誤:

let zombieToUpdate : Zombie? 

for zombieToUpdate in self.zombieArray { 
    if zombieToUpdate.location == thisZombieLocation { 
     let indexOfUpdateZombie = zombieArray.indexOf(zombieToUpdate) 
     self.zombieArray.remove(at: indexOfUpdateZombie) 
     self.zombieArray.append(thisNewZombie) 
    } 
} 

,我發現了以下錯誤:

let indexOfUpdateZombie = zombieArray.indexOf(zombieToUpdate) 
+0

在夫特3,這將是'指數(組成:)','未的indexOf()'。 – rmaddy

+0

我試過了,得到了以下結果:無法用類型爲'(Zombie)'的參數列表調用'index'' –

+0

使您的類型等於或使用'index(where:predicate)'...請參見https:/ /stackoverflow.com/questions/24028860/how-to-find-index-of-list-item-in-swift –

回答

1

由於Zombie不符合:

Cannot convert value of type 'Zombie' to expected argument type '(Zombie) throws -> Bool'

上線時出現此錯誤至Equatable,則不能使用index(of:)

如果您不想添加該功能,您可以選擇實施邏輯。

選項1 - 使用index(where:)

if let index = zombieArray.index(where: { $0.location == thisZombieLocation }) { 
    zombieArray.remove(at: index) 
    zombieArray.append(thisNewZombie) 
} 

無需循環。

選擇2 - 具有索引進行迭代:

for index in 0..<zombieArray.count { 
    let zombieToUpdate = zombieArray[index] 
    if zombieToUpdate.location == thisZombieLocation { 
     zombieArray.remove(at: index) 
     zombieArray.append(thisNewZombie) 
     break // no need to look at any others 
    } 
}