1

In the code below I'm trying to compare the first six bytes of some Data with a utf8 string literal which (in C) I could represent as "\0x93NUMPY". But that's not a valid way of representing a string literal in Swift. So I've used the unicode character u\0093, which is two bytes long in utf8, and indexed the string data from 1..7, which works, but ...Yuk.

let magic = "\u{0093}NUMPY".data(using: .utf8)![1..<7]
guard  Data![0..<6] == magic else {
    return
}

How should I rewrite this code to avoid the confusing indexing issues, while still using a string literal?

1 Answer 1

2

Your method is not only confusing but also error-prone. It works for this particular byte because the UTF-8 representation of U+0093 happens to be C2 93. The same approach with U+00C0 would give the byte 0x80 because the UTF-8 representation is C3 80.

You could use the ISO Latin 1 encoding instead, which maps the Unicode code points U+0000 .. U+00FF to the bytes 0x00 .. 0xFF:

let magic = "\u{0093}NUMPY".data(using: .isoLatin1)!
print(magic as NSData) // length = 6, bytes = 0x934e554d5059}

But actually I would not try to put arbitrary bytes into a string literal but define

let magic = Data([0x93]) + "NUMPY".utf8

instead. Note also that you can check the data for the prefix with

guard data.starts(with: magic) else {
    return
}
2
  • Your second improvement is what I was looking for. I didn't realize that a string literal would get coerced through concatenation. Oct 1, 2020 at 16:13
  • @JoshGreifer: .utf8 returns the “UTF-8 view” of a string, which is a sequence of UInt8 bytes, and that is appended to the Data.
    – Martin R
    Oct 1, 2020 at 16:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.