Here's some code:
var arr1 = [1, 2, 3, 4]
var arr2 = [1, 2, 3, 4]
if arr1 == arr2 {
println("Equal")
} else {
println("Not Equal")
}
// console output: Equal
let slice1 = arr1[0..4]
let slice2 = arr2[0..4]
if slice1 == slice2 {
println("Equal")
} else {
println("Not Equal")
}
// console output: Equal
It's straightforward, but code following:
if arr1[0..4] == arr2[0..4] {
println("Equal")
} else {
println("Not Equal")
}
// console output: Not Equal
Why the result is "Not Equal" rather than "Equal"?
Can I use == operator to compare the value type contents of two arrays or two slices? If not, why I could get the excepted results of the first two if
statement?
I believe this is a compiler bug that did not call the correct
==
overload function to compareSlice
under some conditions.this is the minimum example I came out to produce the problem
In order to see what happened, I put it as a unit test in a Xcode project and check the disassembly code
Start with the correct code:
Xcode give me this
It is not hard to spot this line
overloaded operator
==
is called to compare the valueNow for buggy code
Xcode give me this
I am not expert of assembly code, but a quick scan through the generated comment, I can't see
==
anywhere.Also you can these in the assembly
so I think it is comparing the underlying pointer value instead of the actual content of the slices