I'm trying to write an extension to Data
that allows me to extract it in various casts.
I'm running into a strange problem that I can't quite figure out.
Before I get into generics, I'm trying out fixed data types, and I created this method:
func intValueFromData(_ inData: Data) -> Int64? {
var number = Int64(0)
let len = Swift.min(MemoryLayout<Int64>.size, inData.count)
_ = withUnsafeMutableBytes(of: &number) {
inData.copyBytes(to: $0, from: 0..<len)
}
return number
}
That works. If I do this:
var int_64 = Int64(12345)
var data = Data(bytes: &int_64, count: MemoryLayout<Int64>.size)
let fetched = intValueFromData(data)
fetched becomes "12345" as an Int64.
However, when I try to embed the same method into the Data type, like so:
extension Data {
mutating func intValueFromData() -> Int64? {
var number = Int64(0)
let len = Swift.min(MemoryLayout<Int64>.size, self.count)
_ = withUnsafeMutableBytes(of: &number) {
self.copyBytes(to: $0, from: 0..<len)
}
return number
}
}
I get a compile-time error that says that "withUnsafeMutableBytes(of: &number)
" is not supposed to have an argument.
The last time that I encountered something like this, it turned out that Apple explicitly blocked a functionality, but neglected to tell us in a straightforward manner.
I am not an expert at this kind of thing, but I am wondering if anyone could shed any light on why withUnsafeMutableBytes(of: &number)
behaves differently inside the extension.