extension FileHandle {
func readUInt32() -> UInt32? {
let data = self.readData(ofLength: 4)
guard data.count == 4 else { return nil }
return UInt32(bigEndian: data.withUnsafeBytes { $0.pointee })
}
}
Reading from FileHandlereturns a value Data.
data.withUnsafeBytescauses a closure with a pointer to bytes, here the type of pointer $0is inferred from the context as UnsafePointer<UInt32>.
UInt32(bigEndian:)creates an integer from its big-endian representation as an alternative CFSwapInt32BigToHost().
For additional examples of how to convert from / to Data, see, for example,
round business cards Swift data types to / from data .
source
share