What is the difference between Equal and '==' elements in Swift?

I am looking through the Swift Standard Library, and I came across the elementsEqual method to compare sequences.

I do not see the value of this function, because it will return true only if the order is exactly the same. I figured it would be useful if he could tell me that the two sequences contain the same elements, they just end up in a different order, as this will save me the trouble of sorting both.

Which brings me to my question:

Is there a difference between using elementsEqual and '==' when comparing two sequences? Are there any pros and cons for one versus the other?

I am on my site and wrote the following test:

let values = [1,2,3,4,5,6,7,8,9,10] let otherValues = [1,2,3,4,5,6,7,8,9,10] values == otherValues values.elementsEqual(otherValues)

both of these checks are true, so I cannot distinguish the difference here.

+4
source share
1 answer

After playing with this for a while to find a practical example for the original answer, I found a much simpler difference: C, elementsEqualyou can compare collections of different types, such as Array, RandomAccessSliceand Set, and when ==you cannot do this:

let array = [1, 2, 3]
let slice = 1...3
let set: Set<Int> = [1, 2, 3] // remember that Sets are not ordered

array.elementsEqual(slice) // true
array.elementsEqual(set) // false
array == slice // ERROR
array == set // ERROR

As for a completely different one, @Hamish provided implementation links in the comments below, which I will use for better visibility:

My original answer:

Here is an example of a playground for you that shows that there is a difference:

import Foundation

struct TestObject: Equatable {
    let id: Int
    static func ==(lhs: TestObject, rhs: TestObject) -> Bool {
        return false
    }
}

// TestObjects are never equal - even with the same ID
let test1 = TestObject(id: 1)
let test2 = TestObject(id: 1)
test1 == test2 // returns false

var testArray = [test1, test2]
var copiedTestArray = testArray

testArray == copiedTestArray // returns true
testArray.elementsEqual(copiedTestArray) // returns false

, - , , == - memoryLocationIsEqual || elementsEqual ( , ), elementsEqual , == , elementsEqual .

+2

Source: https://habr.com/ru/post/1680033/


All Articles