I can't figure out how to find index of object in array. For example I have this data structure:
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, ...]
I tried to use personsArray.index(where: ....)
but I don't understand how to use it. index(of: ...)
doesn't work. I think because personsArray
doesn't conform to Equatable
protocol...
Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate.All such elements are returned in a separate array using the filter() method.
function checkIfArrayIsUnique(myArray) { for (var i = 0; i < myArray. length; i++) { for (var j = i+1; j < myArray. length; j++) { if (myArray[i] == myArray[j]) { return true; // means there are duplicate values } } } return false; // means there are no duplicate values. }
Duplicate indexes are those that exactly match the Key and Included columns. That's easy. Possible duplicate indexes are those that very closely match Key/Included columns.
To remove the duplicates from an array of objects: Create an empty array that will store the unique object IDs. Use the Array. filter() method to filter the array of objects. Only include objects with unique IDs in the new array.
index(of: )
gets the Person in your case - it is generic function.
index(where: )
gets the condition for which you want to find particular Person
What you could do:
personsArray.index(where: { $0.name == "person1" })
Or you could send object to:
personsArray.index(of: existingPerson)
For both options you could get nil - you will have to check it for nil (or guard it).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With