How to compare two array of objects?
Assume your data like that:
struct Person
{
let name: String
let id: Int
}
var people1 = [
Person(name: "Quang Hà", id: 42),
Person(name: "Lý Hải", id: 23),
Person(name: "Maria", id: 99)
]
var people2 = [
Person(name: "Maria yyy", id: 99),
Person(name: "Billy", id: 42),
Person(name: "David", id: 23)
]
This is the method to compare two arrays of people with id:
func areArrayPeopleEqual(people1:[Person], people2: [Person]) -> Bool {
var array1 = people1
var array2 = people2
// Don't equal size => false
if array1.count != array2.count {
return false
}
// sort two arrays
array1.sortInPlace() { $0.id > $1.id }
array2.sortInPlace() {$0.id > $1.id }
// get count of the matched items
let result = zip(array1, array2).enumerate().filter() {
$1.0.id == $1.1.id
}.count
if result == array1.count {
return true
}
return false
}
You can try like this:
let result = zip(array1, array2).enumerated().filter() {
$1.0 == $1.1
}.map{$0.0}
Swift 4
The following method makes it much more easy.
Method 1 - Using Equatable Protocol
Step1 - Make your class 'A' equatable as follows
extension A: Equatable {
static func ==(lhs: A, rhs: A) -> Bool {
// Using "identifier" property for comparison
return lhs.identifier == rhs.identifier
}
}
Step2 - Sort your arrays in ascending or descending order
let lhsArray = array1.sorted(by: { $0.identifier < $1.identifier })
let rhsArray = array2.sorted(by: { $0.identifier < $1.identifier })
Step3 - Use == or elementsEqual comparison
let isEqual = lhsArray == rhsArray
OR
let isEqual = lhsArray.elementsEqual(rhsArray, by: { $0 == $1} )
Method 2 (Without Equatable Protocol)
Step 1 - Sort Array as described in Method1, step 2
Step 2 - Use elementsEqual
lhsArray.elementsEqual(rhsArray, by: { $0.identifier == $1.identifier })
Read more about Array Comparison here