【发布时间】:2023-03-25 19:16:01
【问题描述】:
我有一个 Zombie 数组,每个 Zombie 都是一个结构体,如下所示:
struct Zombie {
var number: Int
var location : Int
var health : Int
var uid : String
var group: Int
}
我有一堆僵尸
ZombieArray = [Zombie1, Zombie2, Zombie3]
当它发生变化时我必须更新zombieHealth,但我需要先找到它是哪个Zombie。每个僵尸的位置、编号和 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)
}
}
我收到以下错误:
无法将“Zombie”类型的值转换为预期的参数类型“(Zombie) throws -> Bool”
在线出现此错误:
let indexOfUpdateZombie = zombieArray.indexOf(zombieToUpdate)
【问题讨论】:
-
在 Swift 3 中,它将是
index(of:),而不是indexOf()。 -
我试过了,得到以下结果:无法使用类型为“(的:僵尸)”的参数列表调用“索引”
-
使您的类型 Equatable,或使用
index(where: predicate)... 查看 stackoverflow.com/questions/24028860/… -
您需要使
Zombie符合Equatable协议才能使用index(of:)。如果您不想这样做,请使用index(where:)或获取索引作为迭代的一部分。 -
如:让 indexOfUpdateZombie = self.zombieArray.index(where:zombieToUpdate.location = thisZombieLocation) ??不会运行