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...
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
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