Check the prefix of a Data instance

It's probably a simple problem, but I have trouble figuring it out on my own:

I have a 128-bit Data instance, and I need to check if the first 24-bit of it is 0x18F00D.

What's the best way to do it without using any unsafe operations?

Maybe something like this?

import Foundation

let d = Data([0x18, 0xF0, 0x0D, 0x11, 0xF1, 0x1D])
print(d.subdata(in: 0..<3) == Data([0x18, 0xF0, 0x0D]))
2 Likes

Data is also a Collection of UInt8, so you can do it by comparing to an Array: d.starts(with: [0x18, 0xF0, 0x0D]).

8 Likes