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?
Swift offers both Data
and [UInt8]
types, which do a very similar thing.
[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?
Data
something we are encouraged to use or just to interface with ObjC parts? Do you have popular libraries that use Data
vs [UInt8]
? –
Schreib Data
popular for those? –
Schreib data.base64EncodedStringWithEncoding(NSUTF8StringEncoding)
–
Enthrall NSData
, but if you do some "simple" stuff, you can keep using [UInt8]
. –
Synge Data
does not offer everything that [UInt8]
offers: stackoverflow.com/questions/40190415 –
Schreib [UInt8]
to Data
, at least within the Swift Protobuf project: github.com/apple/swift-protobuf/issues/129 github.com/apple/swift-protobuf/pull/134 –
Kinglet 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)
}
© 2022 - 2024 — McMap. All rights reserved.
Data
(~NSData
) are objects and provide a lot methods that could be useful. But it depends if you need them or not. – Synge