I can't find how to read my data file in swift (converting from Objective-C). The file consists a mixture of bytes, UInt16, UInt32, SInts16 ,strings (as pascal strings), png and mp3 data all mixed up as I use a 'byte' to indicate what sort of data is next.
I tried:-
var data = (NSData)();fileHandle?.readData(ofLength: MemoryLayout.size(ofValue: UInt8()))
But can't use "getBytes etc" so can't get the value.
I thought this would work for UInt16s but no-go
var num = UInt16(); fileHandle?.readData(ofLength: MemoryLayout.size(ofValue: UInt16()))
I'm about to give up and stay with Objective-C.
Any help appreciated.
Paul
Since posting the above, I’ve evolved this idea into something that’s more convenient for the small test projects that I work on every day. Here’s what I now use:
extension Data {
mutating func peekBytes(count: Int) -> Data? {
guard self.count >= count else { return nil }
return self.prefix(count)
}
mutating func parseBytes(count: Int) -> Data? {
guard let result = self.peekBytes(count: count) else { return nil }
self = self.dropFirst(count)
return result
}
mutating func parseBigEndian<T>(_ x: T.Type) -> T? where T: FixedWidthInteger {
guard let bytes = self.parseBytes(count: MemoryLayout<T>.size) else { return nil }
return bytes.reduce(0, { $0 << 8 | T($1) })
}
mutating func parseLittleEndian<T>(_ x: T.Type) -> T? where T: FixedWidthInteger {
guard let bytes = self.parseBytes(count: MemoryLayout<T>.size) else { return nil }
return bytes.reversed().reduce(0, { $0 << 8 | T($1) })
}
}
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"