> On Jun 23, 2015, at 3:21 AM, MiniMonster <
john.m...@md.metrocast.net> wrote:
>
> Say I need to create a file of 100 Double values, store it to a data.dat file, and read it back into an array later for processing. I guess what I'm asking is how to use the foundation framework and swift to create, open, write, read, close, and otherwise manage a stream to/from a file on my hard drive.
{The Swift standard library doesn’t cover I/O (besides println) so this is verging on off-topic, but on the other hand I/O is one of those low-level things that you tend to expect a language’s standard library to cover, so it seems reasonable to talk about it here…}
Streams are given a lot less priority in Foundation than in most other platforms. They exist but they’re not generally used for simple I/O. Instead there are individual method calls that read and write an entire file. I generally like this because it’s less code to write, and it’s probably also somewhat faster. It also gives you some convenient options like an atomic replace (“safe save”) or memory-mapping the data.
The lowest-level file I/O methods are
NSData(contentsOfURL: …, options: …, error: …)
NSData.writeToURL(options: …, error: …)
So what you’d do is get an (unsafe) pointer to your Array, create an NSData from it, then call writeToURL. In the other direction you’d create an NSData with the contents of the file, then use the ‘bytes’ pointer to initialize an Array<Double>.
—Jens