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
  • 298,130
  • 40
  • 468
  • 517
Lucas Farah
  • 892
  • 8
  • 23

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
  • 488,667
  • 78
  • 1,132
  • 1,248