Using NSFileHandle in Swift 3

How can 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)
    }
}
+4
source share
1 answer
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 .

+4
source

Source: https://habr.com/ru/post/1655771/


All Articles