Home > OS >  How to convert data containing various types of int into Swift Int
How to convert data containing various types of int into Swift Int

Time:03-16

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)

How can I convert this type of data into Swift array of Int

CodePudding user response:

You need to do type casting separately.

let list2 = [Int]()
for i in 0..<data.count {
    list2.append(Int(data[i]))
}

CodePudding user response:

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]

  • Related