ios - 查找对象数组的索引

标签 ios arrays swift

<分区>

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

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 协议(protocol)...

最佳答案

index(of: )

在您的案例中获取 Person - 它是通用函数。

index(where: ) 

获取您要为其查找特定人员的条件

你可以做什么:

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

或者您可以将对象发送至:

personsArray.index(of: existingPerson)

对于这两个选项,您都可能得到 nil - 您必须检查它是否为 nil(或保护它)。

关于ios - 查找对象数组的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43628242/

相关文章:

ios - 按名称直接链接到 App Store 中的评论页面,而不是 ID

ios - 生产中的 TestFlight setDeviceIdentifier

ios - 单个 viewController 中的多个 pickerview

arrays - 什么时候将 IFS 设置为 Bash 中的换行符?

swift - 首次应用程序启动时 NavigationBarItem 错位

ios - 不同 View Controller 中的 NSFetchedResultsController 相互更新?

c - 为什么 printf 中不同的数组解引用会给出相同的输出?

python - 追加到 numpy 数组的最佳方式

swift - 如何根据 TableView 单元格中标签(字符串)的长度更改 uiview 的宽度?

swift - 注销按钮崩溃