4

How could I write this method in Swift 3?

extension NSFileHandle {
    func readUInt32() -> UInt32? {
        let data = self.readDataOfLength(4)
        guard data.length == 4 else { return nil }
        return CFSwapInt32HostToBig(UnsafePointer<UInt32>(data.bytes).memory)
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Lucas Farah
  • 1,022
  • 10
  • 24

1 Answers1

4
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 a FileHandle returns a Data value. data.withUnsafeBytes calls the closure with a pointer to the bytes, here the type of the pointer $0 is inferred from the context as UnsafePointer<UInt32>.

UInt32(bigEndian:) creates an integer from its big-endian representation, as an alternative to CFSwapInt32BigToHost().

For more examples on how to convert from/to Data, see for example round trip Swift number types to/from Data.

Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382