Search code examples
swiftnsdate

How to read partially a Data object


The recent change in Swift 4 provides the simple way to initialize a byte array with your Data object. The result gets you an [UInt8] with the whole data stored into it.

let array = [UInt8](data)

I can't find the solution to load the same Data object only partially using an offset and a length. Is it possible without slicing the whole array or should I switch to InputStream?


Solution

  • You can slice a Data object with a subscript.

    For example, you just want the 3rd to 5th index in the data, you would use

    data[3..<6]
    

    In your case, you would do

    let array = [UInt8](data[lowerIndex..<upperIndex])
    

    where lowerIndex and upperIndex are the indexes.