arrays - 在基于 1 个 SWIFT 组件的结构数组中查找索引

标签 arrays swift struct

我有一个 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/

相关文章:

c - 如何将内存分配给空字符串数组

表示文件路径的 PHP 多维数组

c++ - 全局字符数组不会被重新分配或正确输出

ios - 获取 CoreData 时因内存问题而终止

swift - 标签未显示(Swift 4 SpriteKit)

c - 函数声明中 '(const struct namect*)' 背后的含义是什么?

arrays - 如何在 Go 中将结构添加到结构数组

python - 从两个 numpy 数组中随机选择元素

ios - TableView 的 Swift 问题

c - c 中多线程的错误输出?