91

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?

0

7 Answers 7

128

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))
10
  • 2
    @califrench I'm sorry, I didn't follow. 1) There is no NSArray that I can spot, the bytes accessor does not return it. 2) What errors would it cause down the road? If you're referring to possible unavailability of NS* classes, recall that the question specifies NSData.
    – Arkku
    May 24, 2016 at 21:35
  • 1
    I'm sorry @Arkku, I got confused, I was thinking for a minute that Array() was relying on NSArray but I don't think it is... The issues down the road would have been trying to access an element using a subscript since NSArrays don't know what kind of elements they contain whereas Swift Arrays do.
    – califrench
    May 25, 2016 at 22:19
  • 1
    @Dan It works just fine for me both in Swift 2.2 and Swift 3. In Swift 3 the preceding line is let data : NSData! = "foo".data(using: String.Encoding.utf8)
    – Arkku
    Jun 26, 2016 at 11:11
  • 1
    @Arkku it doesn't compile with latest Swift, I had to change it to: array = data.withUnsafeBytes { bytes in Array( UnsafeBufferPointer(start: bytes, count: data.count) ) }
    – Zmey
    Jun 30, 2016 at 0:07
  • 1
    @LeoDabus That's basically a different way of saying [UInt8](data), which is already in the answer since the latest edit. (And IMO the clearer syntax with explicit type.)
    – Arkku
    Dec 13, 2016 at 20:21
80

Swift 5 Solution

Data to [bytes]

extension Data {
    var bytes: [UInt8] {
        return [UInt8](self)
    }
}

[bytes] to Data

extension Array where Element == UInt8 {
    var data: Data {
        return Data(self)
    }
}
4
  • 1
    Data(bytes:(self)) is deprecated in Swift 5 :'(
    – vmeyer
    May 16, 2019 at 10:44
  • 1
    great answer, elegant af
    – Woodstock
    Feb 27, 2020 at 15:47
  • Apologies if this is a silly question, but this would produce a copy, right? Jun 12, 2020 at 16:20
  • @TobiSchweiger yes because arrays are always value types in Swift, so arrays always copy Jul 27, 2023 at 20:06
49

It's funny but exist more simple solution. Works in Swift 3. Surely. I've used this today.

data: Data // as function parameter    
let byteArray = [UInt8](data)

That's all! :) NSData easily bridged to Data.

UPDATE: (due to Andrew Koster comment)

Swift 4.1, Xcode 9.3.1

Just has been rechecked - all works as expected.

if let nsData = NSData(base64Encoded: "VGVzdFN0cmluZw==", options: .ignoreUnknownCharacters) {
let bytes = [UInt8](nsData as Data)
print(bytes, String(bytes: bytes, encoding: .utf8))

Output: [84, 101, 115, 116, 83, 116, 114, 105, 110, 103] Optional("TestString")

2
  • 1
    This should be the accepted solution, now that Swift 3 is out.
    – Chrissi
    Nov 14, 2016 at 16:48
  • This most likely makes a copy of your data. While small, not a big deal. If large, can cause a lot of issues.
    – Luke
    Nov 14, 2016 at 21:24
22

You can use the getBytes function of NSData to get the byte array equivalent.

As you did not provide any source code, I will use a Swift String contents that has been converted to NSData.

var string = "Hello World"
let data : NSData! = string.dataUsingEncoding(NSUTF8StringEncoding)

let count = data.length / sizeof(UInt8)

// create an array of Uint8
var array = [UInt8](count: count, repeatedValue: 0)

// copy bytes into array
data.getBytes(&array, length:count * sizeof(UInt8))

println(array)

Swift 3/4

let count = data.length / MemoryLayout<UInt8>.size

// create an array of Uint8
var byteArray = [UInt8](repeating: 0, count: count)
// copy bytes into array
data.getBytes(&byteArray, length:count)
1
  • 3
    For swift 3 replace sizeof(UInt8) with MemoryLayout<UInt8>.size
    – Marek H
    Sep 5, 2016 at 8:54
7

Swift 3/4

let data = Data(bytes: [0x01, 0x02, 0x03])
let byteArray: [UInt8] = data.map { $0 }
1

swift 4 and image data to a byte array.

 func getArrayOfBytesFromImage(imageData:Data) ->[UInt8]{

    let count = imageData.count / MemoryLayout<UInt8>.size
    var byteArray = [UInt8](repeating: 0, count: count)
    imageData.copyBytes(to: &byteArray, count:count)
    return byteArray

}
0

You can try

extension Data {
func toByteArray() -> [UInt8]? {
    var byteData = [UInt8](repeating:0, count: self.count)
    self.copyBytes(to: &byteData, count: self.count)
    return byteData
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.