In this short article we explore when two array are equal in Swift.
Let’s start we the obvious cases:
1 2 3 4 |
let a = [1, 2, 3] let b = [1, 2, 3] a == b |
a == b is true as expected.
Let’s now test the following case
1 2 3 4 |
let a = [1, 2, 3] let b = [1, 3, 2] a == b |
a == b is false.
In order two array to be equal they have to have the same elements in the same order.
Let’s see what happens when we have classes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
class A: Equatable { static func == (lhs: A, rhs: A) -> Bool { lhs.i == rhs.i } let i: Int init(i: Int) { self.i = i } } let a = [A(i: 1), A(i: 2)] let b = [A(i: 1), A(i: 2)] let c = a let d = [A(i: 2), A(i: 1)] a == b a == c b == c a == d |
a == b, a == c and b == c are true.
The same logic applies. In order to be equal each element on the same position has to be equal.