0

I'm trying to read data from a large file in Swift -- I don't want the whole file read into a NSData object, which seems to be how Swift wants to do everything.

I found the code to open the file with a FileHandle and read chunks of data into NSData objects. But I can't figure out how to convert the data to the right format. Everything I've seen online says this should work to convert an NSData chunk to an Int:

 let dataSize = MemoryLayout<Int>.size
 let data = handle.readData(ofLength: dataSize)
 if data.count < dataSize { throw CocoaError(.fileReadCorruptFile) }

 var i:Int = 0
 data.getBytes(&i, length: dataSize) 

But it won't compile. It says

'&' used with non-inout argument of type 'Int'.  

I don't get why it says that. I use data.getBytes in other parts of my project in the same way with no problem. Is there something different about the NSData object returned from handle.readData?

Thanks!

bsabiston
  • 721
  • 6
  • 22
  • try `let i: Int = data.withUnsafeBytes({$0.pointee})` – Leo Dabus May 02 '18 at 16:35
  • The error message indicates that your data has the type `Data` and not `NSData` – Possibly helpful: [round trip Swift number types to/from Data](https://stackoverflow.com/questions/38023838/round-trip-swift-number-types-to-from-data) – Martin R May 02 '18 at 16:37
  • 1
    Leo, that worked, thanks! Martin yeah I meant to say Data instead of NSData but that wasn't the issue. However it looks like the link you provided would have worked too... – bsabiston May 02 '18 at 16:43

0 Answers0