Swift offers both Data
and [UInt8]
types, which do a very similar thing.
Int8 is an Integer type which can store positive and negative values. UInt8 is an unsigned integer which can store only positive values.
It is a collection of bytes ( [UInt8] array of unsigned integer 8 bits 0-255).
[UInt8]
is essentially a byte array, a byte (as I'm sure you know), is comprised of 8 bits. Whilst NSData isn't simply a byte array, deep down it's underlying structure is based off one. You can easily convert between them using methods such as data.bytes
, for example.
In terms of designing APIs, I would personally recommend you design them with NSData simply because of all the extra functionality it offers over a simple byte array. Apple has already done a lot of the legwork for you, so why do it again yourself?
I prefer using Data
for most things, but [UInt8]
has one distinct advantage: you can pass it directly to functions requiring pointers to the bytes like C functions, whereas for Data
you have to do a bunch more gymnastics. The code below demonstrates the difference for both immutable and mutable arrays and Data
objects.
func takesAPointer(_ p: UnsafePointer<UInt8>) {
// ...
}
let a: [UInt8] = [1, 2, 3]
takesAPointer(a)
let d = Data([1, 2, 3])
d.withUnsafeBytes {
let p = $0.bindMemory(to: UInt8.self).baseAddress!
takesAPointer(p)
}
func takesAMutablePointer(_ p: UnsafeMutablePointer<UInt8>) {
// ...
}
var b: [UInt8] = [1, 2, 3]
takesAMutablePointer(&b)
var e = Data([1, 2, 3])
e.withUnsafeMutableBytes {
let p = $0.bindMemory(to: UInt8.self).baseAddress!
takesAMutablePointer(p)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With