How do I open a file in Swift?

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.


Here's a way to do it if the file is in your iOS project (hoping this is your situation):

var filePath = Bundle.main.path(forResource: "theFile", ofType: "txt")
var data     = Data(contentsOf: URL(fileURLWithPath: filePath))

If you just need to read the contents of a file into a string, a Swift 2.0 way to do it is this:

do {
    var dictionary = try String(contentsOfFile: "/usr/share/dict/words", encoding: NSUTF8StringEncoding)
} catch {

}

Otherwise, the more involved methods mentioned above works.

Tags:

Io

File

Swift