Hello, I have problem with fallowing code, where I want to unwrap value returned by .withUnsafeBytes(_:). Sometimes (with exactly same data) it unwraps property properly and sometimes don't.
func testGuardLet() {
let data = Data(bytes: [7, 0, UInt8.min])
let sizeData = data.subdata(in: 0 ..< 2)
let size: Int? = sizeData.withUnsafeBytes { $0.pointee }
guard let unwrappedSize = size else {
print("failure: \(String(describing: size))")
XCTFail()
return
}
print("success: \(unwrappedSize)")
}
You've made a Data that's three bytes long, then you limit it to two bytes, then you try to read an Int? out of it, which is nine bytes and also isn't guaranteed to have any particular representation. What are you really trying to do?
Example code is just narrow way how to reproduce the bug. In nutshell I need to concatenate multiple chunks of data to one piece and first two bytes of first chunk represents size of concatenated data.
:-/ "It works for me" with Xcode 10. Here's the test case I used:
import Foundation
func test(sizeData: Data) {
let size = sizeData.withUnsafeBytes {
(pointer: UnsafePointer<UInt16>) in
pointer.pointee
}
}
If you can reproduce your issue in a self-contained test case, please file a bug about that error message! Most likely the actual problem is something else.
(Note that I stopped specifying the type of size. There's no reason for it to be Optional, but it also can't be an Int because you're only reading two bytes. You'll have to convert the result to Int yourself.)