数组是否包含对象并获取数组的索引

时间:2017-12-31 04:40:56

标签: struct swift4

我正在使用以下代码,需要实现两件事:

  1. 获取person1的索引
  2. 确定列表是否包含person1

    struct person {
    var name : String
    var id : String
    }
    var list : [person] = []
    
    let person1 =  person.init(name: "pankaj", id: "123")
    
    list.append(person.init(name: "Gaurav", id: "1234"))
    list.append(person.init(name: "Naresh", id: "1223"))
    list.append(person.init(name: "pankaj", id: "123"))
    list.append(person.init(name: "rahul", id: "345"))
    

1 个答案:

答案 0 :(得分:0)

您可以通过确认等同协议来实现这一目标

struct Person : Equatable{
var name : String
var id : String
// here is the function which return true if compared objects are equal else it returns false
static func == (lhs: Person, rhs: Person) -> Bool {
            return lhs.name == rhs.name && lhs.id == rhs.id
        }

}
var list : [Person] = []
list.append(Person.init(name: "Gaurav", id: "1234"))
list.append(Person.init(name: "Naresh", id: "1223"))
list.append(Person.init(name: "pankaj", id: "123"))
list.append(Person.init(name: "rahul", id: "345"))
let person1 =  Person.init(name: "pankaj", id: "123")
// here you will be not able to access list.index(of: person1) method until you confirm to Equatable protocol
// here you get index of person1 in list
if let index = list.index(of: person1){
print("matched index is \(index)")
}else{
print("not matched")
}
//you can use this method only if you confirm to equatable protocol
// It returns true if person1 is in list otherwise returns false
list.contains(person1)