2017-05-09 Check PDF file header with Swift

Here's a little Swift playground that shows how you can check whether a Data object (for example from a file) is a PDF. It's done by checking the first couple of bytes.

    import UIKit
    // http://stackoverflow.com/a/26503955/1085556
    func dataWithHexString(hex: String) -> Data {
        var hex = hex
        var data = Data()
        while(hex.characters.count > 0) {
            let c: String = hex.substring(to: hex.index(hex.startIndex, offsetBy: 2))
            hex = hex.substring(from: hex.index(hex.startIndex, offsetBy: 2))
            var ch: UInt32 = 0
            Scanner(string: c).scanHexInt32(&ch)
            var char = UInt8(ch)
            data.append(&char, count: 1)
        }
        return data
    }
    struct HeaderError: Error {
    }
    // http://stackoverflow.com/a/17280876/1085556
    let smallestPDFasHex = "255044462D312E0D747261696C65723C3C2F526F6F743C3C2F50616765733C3C2F4B6964735B3C3C2F4D65646961426F785B302030203320335D3E3E5D3E3E3E3E3E3E"
    let data = dataWithHexString(hex: smallestPDFasHex)
    let headerRange: Range<Data.Index> = 0..<4
    let header = data.subdata(in: headerRange)
    guard let headerString = String(data: header, encoding: .ascii) else {
        print("Header not found")
        throw HeaderError()
    }
    if headerString == "%PDF" {
        print("It's a PDF")
    } else {
        print("It's NOT a PDF")
    }