【问题标题】:Find index of objects array [duplicate]查找对象数组的索引[重复]
【发布时间】:2017-04-26 16:25:47
【问题描述】:

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

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 协议...

【问题讨论】:

标签: ios arrays swift


【解决方案1】:
index(of: )

在您的情况下获取 Person - 它是通用函数。

index(where: ) 

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

你能做什么:

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

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

personsArray.index(of: existingPerson)

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

【讨论】:

  • index(of: ) 不编译(。谢谢分享,我会用(where: $0.name == ...)
  • 不要忘记 {} for where 和 for index(of: ) 你需要提供数组的实际对象
【解决方案2】:

从我的角度来看,只需与=== 进行比较。

小例子。

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

getPersonIndex(from: personsArray, user: person2)

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 2019-09-08
      • 1970-01-01
      • 2017-02-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多