'How to convert data containing various types of int into Swift Int
I receive Data type object which inside is list of uint8_t, uint16_t, uint32_t(mix typed list). I need to convert this data into swift array of Int. I cannot do the followings since data contains multiple types of int
let list = [Uint8](data)
let list2 = [Int](data)
Data order
- data1: uint8_t
- data2: uint32_t
- data3: uint16_t
How can I convert this type of data into Swift array of Int
Solution 1:[1]
You need to do type casting separately.
let list2 = [Int]()
for i in 0..<data.count {
list2.append(Int(data[i]))
}
Solution 2:[2]
As Data are bytes [UInt8] (with capital I) and Data are interchangeable.
For [uint16_t] and [uint32_t] use MartinR's Data extension
extension Data {
init<T>(fromArray values: [T]) {
self = values.withUnsafeBytes { Data($0) }
}
func toArray<T>(type: T.Type) -> [T] where T: ExpressibleByIntegerLiteral {
var array = Array<T>(repeating: 0, count: self.count/MemoryLayout<T>.stride)
_ = array.withUnsafeMutableBytes { copyBytes(to: $0) }
return array
}
}
And an example, uint16Bytes represents an array of [UInt16] although the type is [UInt8]
let uint16Bytes : [UInt8] = [0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x04, 0x00]
let uint16Data = Data(uint16Bytes)
let array = uint16Data.toArray(type: UInt16.self).map(Int.init) // [1, 2, 3, 4]
toArray returns [UInt16]. You have to map the array to [Int]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Imran0001 |
| Solution 2 | vadian |
