I would guess that if data != originalData then they are not equal and perhaps something is lost in the string formatting?
Out of curiosity what happens if you add the following:
var index = 0
for (byte1, byte2) in zip(data, originalData) {
if byte1 != byte2 {
print("\(byte1), != \(byte2) at index \(index)")
}
index += 1
}
I assume that Data's equality check checks that the contents are the same, and not that both data have the same pointer. That seems to be true for the Foundation rewrite anyway...
It's quite easy for strings constructed from non identical data end up being equal.
Edited out: see my post below.
I'd recommend to go through data byte by byte and see where the difference is:
// could be typos as I'm typing this in a browser window
precondition(data1.count == data2.count)
for i in 0 ..< data1.count {
if data1[i] != data2[i] {
print("first difference found at \(i) offset, \(data[i] != data2[i])")
break // comment this out to see all differences
}
}
AFAICT the code you use to render the data to a string is correct, which makes it a bit of a mystery as to why this is failing. I’d also like to see the results of the byte-by-byte comparison test suggested by Diggory and tera.
I see the pointer values are different, which could be the reason?
That shouldn’t be the reason. Consider this code:
let d1 = Data("Hello Cruel World!".utf8)
let d2 = Data("Hello Cruel World!".utf8)
The resulting pointers are different but the values compare equal:
Quinn is right. I didn't pay attention to the format string: what you written initially should work as you are converting data to a hex string. I'm curious why it doesn't work for you.
BTW, I've seen instances when debugger lied to be, e.g. showing true for false or vice versa. "print" the result of comparison to be sure.
When I wrote my tiny test code I found that my two datas had the same pointerValue - is that because when the data are small enough, they can be packed together into the size of one pointer? (like small strings?)
Or is this a bug in Xcode?
import Foundation
let hello = "Hello"
var hello2 = "Hell"
hello2.append("a")
let data1 = Data(hello.utf8)
let data2 = Data(hello2.utf8)
if data1 == data2 {
print("data1 == data2 is true")
}
// BREAKPOINT HERE
var index = 0
for (byte1, byte2) in zip(data1, data2) {
if byte1 != byte2 {
print("\(byte1), != \(byte2) at index \(index)")
}
index += 1
}