查找对象数组的索引

16

我不知道如何在数组中查找对象的索引。例如,我有这个数据结构:

class Person {
var name: String
var age: Int

init(name personName: String, age personAge: Int) {
    self.name = personName
    self.age = personAge
  }
}

let person1 = Person(name: "person1", age: 34)
let person2 = Person(name: "person2", age: 30)
...
var personsArray = [person1, person2, ...]

我尝试使用 personsArray.index(where: ....),但是我不知道如何使用它。index(of: ...) 不起作用。我想这是因为 personsArray 没有遵循 Equatable 协议...


如果您想查找相同的对象,请使用https://dev59.com/VWAg5IYBdhLWcg3wDHU3#32923407。 - Martin R
3个回答

27
index(of: )

获取你的情况中的人 - 这是一个通用函数。

index(where: ) 

获取您想要查找特定人员的条件。

您可以做以下事情:

personsArray.index(where: { $0.name == "person1" })

或者您可以发送对象到:

personsArray.index(of: existingPerson)

对于这两个选项,你可能会得到nil - 你需要检查它是否为nil(或者使用guard语句)。


index(of: ) doen't compile ( . Thanks for sharing, I will use (where: $0.name == ...) - Alex_slayer
不要忘记在 where 和 index(of: ) 中使用 {},你需要提供数组的实际对象。 - Miknash

5

在我看来,只需要与===进行比较即可。

以下是一个小例子。

func getPersonIndex(from: [Person], user: Person) -> Int? {
    return from.index(where: { $0 === user })
}

getPersonIndex(from: personsArray, user: person2)

0
我找到了如何使用.index(where...

personsArray.index { (item) -> Bool in item.name == "person2" && item.age == 30 }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接