Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSData to [Uint8] in Swift

Tags:

swift

nsdata

I couldn't find a solution to this problem in Swift (all of them are Objective-C, and they deal with pointers which I don't think exist in Swift in the same form). Is there any way to convert a NSData object into an array of bytes in the form of [Uint8] in Swift?

like image 470
Bowen Su Avatar asked Aug 05 '15 00:08

Bowen Su


People also ask

What is NSData in Swift?

NSData is toll-free bridged with its Core Foundation counterpart, CFData . See Toll-Free Bridging for more information on toll-free bridging. Important. The Swift overlay to the Foundation framework provides the Data structure, which bridges to the NSData class and its mutable subclass NSMutableData .

What is byte array in Swift?

In Swift a byte is called a UInt8—an unsigned 8 bit integer. A byte array is a UInt8 array. In ASCII we can treat chars as UInt8 values. With the utf8 String property, we get a UTF8View collection. We can convert this to a byte array.


1 Answers

You can avoid first initialising the array to placeholder values, if you go through pointers in a slightly convoluted manner, or via the new Array constructor introduced in Swift 3:

Swift 3

let data = "foo".data(using: .utf8)!  // new constructor: let array = [UInt8](data)  // …or old style through pointers: let array = data.withUnsafeBytes {     [UInt8](UnsafeBufferPointer(start: $0, count: data.count)) } 

Swift 2

Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>(data.bytes), count: data.length)) 
like image 76
Arkku Avatar answered Oct 13 '22 04:10

Arkku