例如,我有以下课程:
class Person: Any {
dynamic var name: String = ""
dynamic var surname: String = ""
}
另外,我有以下数组,其中包含“Person”类的实例:
let person1 = Person(); person1.name = "John"; person1.surname = "Smith"
let person2 = Person(); person2.name = "Ivan"; person2.surname = "Ivanov"
let person3 = Person(); person3.name = "Sam"; person3.surname = "Woodman"
let personList = [person1, person2, person3]
有没有办法以某种方式获得所有约翰斯的索引?
答案 0 :(得分:5)
您可以flatMap
将您的人员列表作为枚举列表,以便返回匹配的偏移量。
let indexes = personList.enumerated().flatMap { $1.name == "John" ? $0 : nil }
否则,您可以通过简单的for循环实现此目的。
var indexes = [Int]()
for index in personList.indices {
if personList[index].name == "John" {
indexes.append(index)
}
}
print(indexes)