Home > Software engineering >  What is the better/best way of slicing Swift Data by size?
What is the better/best way of slicing Swift Data by size?

Time:09-17

I want to slice a Data type variable by specifying the memory size. Let's say I want to have only initial 1,000 bytes of an audio file. I'm trying the following code. Both variables point to the same memory address but the sizes differ as expected so seems to work but not sure if it really does.

let original = try! Data(contentsOf: URL(string: "https://example.com/audio.mp3")!)
let sliced = original[0..<1_000] // e.g. Only 1000 bytes (I understand the range can not be beyond the actual original data size)
  • Does the above code work as I expect?
  • Any concern with the above approach?
  • Any better way to realize the same?

CodePudding user response:

A Data slice (as returned by the range-subscript operator you're using, and methods like prefix, suffix, etc.) shares storage with its “parent” Data unless the slice is small enough to be stored inline in the Data struct itself. (I believe the maximum size for inline data on 64-bit platforms is 14 bytes.)

You can find the implementation of Data for Apple platforms here:

https://github.com/apple/swift-corelibs-foundation/blob/main/Darwin/Foundation-swiftoverlay/Data.swift

For other platforms, the implementation is here:

https://github.com/apple/swift-corelibs-foundation/blob/main/Sources/Foundation/Data.swift

  • Related