let bigNum = data.withUnsafeBytes { $0.load(as: UInt64.self) }
That's safe if data is 8-byte aligned. And it's currently the best way to do it IMO. In the past I've suggested adding Data APIs to bypass the unsafe closure-based API, like this, but we're not there yet:
e.g. let bigNum = data.load(as: UInt64.self) }
We also don't have an API for loading unaligned data, so if alignment can't be guaranteed you still have to do something like this:
One additional question: would
let subdata = data.subdata(in: 3 ..< 3 + 8)
be 8-byte aligned?
But I find this all very confusing.
I really would like to write:
let bigNum = UInt64(data: data)
or:
let bigNum = UInt64(data: data, offset: 7)
and would expect nil (if data is too short) or a value.
Even better (as I am receiving data in network byte order) would be:
let bigNum = UInt64(data: data, endianness: .bigEndian) // converts from bigEndian to host endianness
No, unless data happened to be misaligned to begin with.
I really would like to write:
let bigNum = UInt64(data: data)
or:
let bigNum = UInt64(data: data, offset: 7)
and would expect nil (if data is too short) or a value.
I suppose extensions could be provided for the scalar types. I don't think it can replace a generic copyBytes API. Note that Data APIs use indices instead of byte offsets. I also think it's more conventional for Swift libraries to trap on something the user would normally check for themselves rather than force the user to unwrap an optional.
Even better (as I am receiving data in network byte order) would be:
let bigNum = UInt64(data: data, endianness: .bigEndian) // converts from bigEndian to host endianness
I think the conventional way to do it is UInt64(data: data).bigEndian
Actually, I agree with your original suggestion. I added a note about this to the JIRA bug.