0

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!

2
  • 3
    Looks like a tuple with 4 UInt8 values. Commented Oct 2, 2018 at 17:30
  • Superb! Indeed. Thanks! Commented Oct 2, 2018 at 17:37

1 Answer 1

1

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)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.