swiftswift3nsfilehandle

Using NSFileHandle on Swift 3


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)
    }
}

Solution

  • 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.