Search code examples
fileioswift

How do I open a file in Swift?


I have yet to see documentation of a Swift standard library, where I would expect to find something like a File class or struct with an interface for opening, reading, and writing files. All the usual stuff you expect for File IO. Is there one, or are to depend on NSFileManager and its ilk?


Solution

  • The Swift standard library does not include this functionality. The standard library mainly contains data structures, low-level types and calls, and semi-built-in language features; I/O beyond print() and readLine() is considered out of scope. I don't really expect this to change in the near future, either.

    However, Foundation contains file I/O calls, and the Swift Corelibs project is working hard to reimplement Foundation in pure Swift so it's available everywhere Swift is. The POSIX I/O calls available on every major operating system are also available in Swift, although they're much clumsier to use.