Mike Nathas
Mike Nathas

Reputation: 1393

Convert Array-looking variable to Data in Swift

I want to convert an (at least I think) array of UInt8 values to Data.

Using Data(bytes: variable) does not work here.

Here's the type of the variable:

po type(of: obj.variable)   
(Swift.UInt8, Swift.UInt8, Swift.UInt8, Swift.UInt8)

It seems that this isn't an array of UInt8 but what type is it and how can I convert it to a Data?

Thanks!

Upvotes: 0

Views: 280

Answers (1)

Palle
Palle

Reputation: 12109

The type of obj is a tuple of four UInt8 values.

You can access elements of the tuple as follows:

let obj: (UInt8, UInt8, UInt8, UInt8) = (2, 4, 6, 8) // let obj be a tuple of four UInt8 values
obj.0  // 2
obj.1  // 4

As Data is effectively a Collection of bytes, it can be initialized from a sequence of UInt8 values.

So the easiest solution would just be to create an Array from the elements of the tuple and initialize a Data value from it:

let data = Data([obj.0, obj.1, obj.2, obj.3])

This is however not the most general solution and only works when the tuple only contains UInt8 values.

A more general approach would be to convert the tuple to an UnsafePointer first and create a Data value from it:

let data = withUnsafePointer(to: &obj) { ptr -> Data in
    return Data(bytes: ptr, count: MemoryLayout.size(ofValue: obj)
}

Upvotes: 1

Related Questions