I do a bunch of work with [Uint8]
arrays. But I often have to recast these as NSData
objects to interface with iOS frameworks such as CoreBluetooth
. So I have lots of code that might look something like:
var input:[UInt8] = [0x60, 0x0D, 0xF0, 0x0D]
let data = NSData(bytes: input, length: input.count)
Being tired of having to insert this extra let data = ...
line, I thought I would just extend those arrays with a computed property to do the work. Then I could just do things like:
aBluetoothPeriperal.write(myBytes.nsdata, ...)
So it's basically just extension sugar. I can't extend Array, but I can extend a protocol:
extension SequenceType where Generator.Element == UInt8 {
var nsdata:NSData {
return NSData(bytes: self, length: self.count)
}
}
Which produces an error that looks like:
Playground execution failed: MyPlayground.playground:3:24: error: cannot convert value of type 'Self' to expected argument type 'UnsafePointer<Void>' (aka 'UnsafePointer<()>')
return NSData(bytes: self, length: self.count)
^~~~
Sadly, the more I use Swift--and I really do like some things about Swift--the more I'm reminded of my negative experiences with trying to understand reams of unhelpful compiler output when I tried my hand at C++ with lots of generics and stuff years ago. So please Obi Wan, help me see the light here!