Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data vs [UInt8]

Tags:

swift

nsdata

Swift offers both Data and [UInt8] types, which do a very similar thing.

  • What are the differences between the two?
  • When designing new API's, what's the preferred type?
like image 324
Etan Avatar asked Oct 05 '16 11:10

Etan


People also ask

What is the difference between Uint and UInt8?

Int8 is an Integer type which can store positive and negative values. UInt8 is an unsigned integer which can store only positive values.

What is data in Swift?

It is a collection of bytes ( [UInt8] array of unsigned integer 8 bits 0-255).


2 Answers

[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?

like image 91
Jacob King Avatar answered Sep 23 '22 07:09

Jacob King


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)
}
like image 34
Wolf McNally Avatar answered Sep 26 '22 07:09

Wolf McNally