I am finding Swift
and NSData
to be an unholy matrimony of frustration. I find I feel like all the supposed new found Swift safety goes out the window every time I deal with this thing. The amount of crashes (with unhelpful traces) don't help.
So, I've learned, that I can avoid the scary UnsafeMutablePointer
stuff by doing things like the following:
var bytes = [UInt8](count: 15, repeatedValue: 0)
anNSData.getBytes(&bytes, length=15)
I also discovered, that I can extract directly into singular values:
var u32:UInt32 = 0
anNSData.getBytes(&u32, length=4)
This leads to two intermediate questions:
1) Is there something I can use that is more reliable than hardcoded constants there. If this were C, I'd just use sizeof
. But I think I read that maybe I should be using strideof
instead sizeof
? And that wouldn't work on [UInt8]
's, would it?
2) The docs (for Swift) says that this parameter is supposed to be _ buffer: UnsafeMutablePointer<Void>
. So how does this work? Am I just getting lucky? Why would I want to do that instead of the more native/managed [Uint8] construct?? I wondered if UnsafeMutablePointer
was a protocol, but it's a struct.
Emboldened with reading the values directly (rather than as an Array), I thought maybe I could try another kind of struct. I have a 6 byte struct that looks like:
struct TreeDescription : Hashable {
var id:UInt32 = 0x00000000
var channel:UInt8 = 0x00
var rssi:UInt8 = 0x00
var hashValue:Int {
return Int(self.id)
}
}
Which actually works (after thinking it didn't, but eventually doing a clean which made some crashes go away)!
var tree = TreeDescription()
anNSData.getBytes(&newTree, length: 6)
But this leads me to worries about structure packing details? Why does this work? What should I be worrying about doing this?
This all feels very C-ish to me. I thought Swift took the C out of ObjectiveC.