Difference Between “==“ and “.elementEqual” | Swift | iOS
==(_:_:)
Returns a Boolean value indicating whether two arrays contain the same elements in the same order.
Then I found out about the elementsEqual(_:) that seemed the same to me, so I read it to know what the difference.
elementsEqual(_:)
Returns a Boolean value indicating whether this sequence and another sequence contain the same elements in the same order.
elementEqual is a instance method which take O(m) time complexity and with elementsEqual
you can compare collections of different types such as Array
, RandomAccessSlice
and Set
, while with ==
you can't do that.
let arrOfChocolate = [1, 2, 3]
let sliceOfChocolate = 1...3
let setOfChocolate: Set<Int> = [1, 2, 3] // remember that Sets are not ordered
arrOfChocolate.elementsEqual(sliceOfChocolate) // true
arrOfChocolate.elementsEqual(set) // false
arrOfChocolate == sliceOfChocolate // ERROR
arrOfChocolate == setOfChocolate // ERROR
I hope that this small piece of logic has become clear. 😊
Thank you 😄