How to idiomatically read/write binary file with Swift?


I want to read a binary file into swift data structures, and then perhaps write it back after processing.

What would be the idiomatic way to do that? I know how to do it in Objective-C, but I would like to try Swift for this, in the most "Swifty" way as possible. I am a Swift newbie, but I am willing to learn.

FWIW, The binary file is organized as a tree of typed "chunks", potentially nested, where the first field for a chunk is its length. Data is encoded big-endian.

Thanks for any pointer/general outline

I'd just use InputStream or, if the files aren't going to be especially big, just read the whole thing using Data.init(contentsOf url: URL, options: Data.ReadingOptions = []) throws and go from there.

In principle the answer to this question is to implement Codable’s Decoder and Encoder protocols for your binary file format. However, in this case the devil is in the details: if your data types greatly diverge from what Codable expects than you may find this to be somewhat awkward.

Otherwise, there is no consensus on what the most Swifty way to do this is. SwiftNIO has a custom ByteBuffer data type that provides helpers for doing this with network protocols, and is generally pretty handy, but it has never been extended for use with file I/O and is unlikely to be due to SwiftNIO’s focus on asynchronicity. That said, many of the parsing helpers could just as easily be implemented on top of something like Data if you were willing to only implement the read/write functions.

Terms of Service

Privacy Policy

Cookie Policy