我有一个 Zombie 数组,每个 Zombie 都是一个结构体,如下所示:
struct Zombie {
var number: Int
var location : Int
var health : Int
var uid : String
var group: Int
}
我有一系列僵尸
ZombieArray = [Zombie1, Zombie2, Zombie3]
当僵尸健康发生变化时,我必须更新它,但我需要首先找到它是哪个僵尸。每个僵尸的位置、编号和 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)
}
}
我收到以下错误:
Cannot convert value of type 'Zombie' to expected argument type '(Zombie) throws -> Bool'
此错误发生在线路上:
let indexOfUpdateZombie = zombieArray.indexOf(zombieToUpdate)
最佳答案
由于 Zombie
不符合 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
}
}
关于arrays - 在基于 1 个 SWIFT 组件的结构数组中查找索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45664875/