Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two array of objects?

I have a class A:

class A {
   var identifier: String?
   var quantity: Int = 0
}

Two arrays of A instances:

var array1: [A] = [a1, a2, a3, a4]
var array2: [A] = [a5, a6, a7, a8]

I don't know which is the best way to check: array1==array2 if a1.identifier == a5.identifier, a2.identifier == a6.identifier, a3.identifier==a7.identifier, a4.identifier==a8.identifier in Swift.

Please help me...

like image 730
Quang Hà Avatar asked Aug 26 '16 07:08

Quang Hà


1 Answers

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

like image 72
Anand Avatar answered Sep 21 '22 15:09

Anand