【问题标题】:Find an index in an array of structs based on 1 component SWIFT基于 1 个组件 SWIFT 在结构数组中查找索引
【发布时间】: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) ??不会运行

标签: arrays swift struct


【解决方案1】:

由于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
    }
}

【讨论】:

    猜你喜欢
    • 2018-02-10
    • 1970-01-01
    • 2019-09-04
    • 2021-07-13
    • 1970-01-01
    • 2015-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多