How can I read a file in a swift playground

While the answer has been supplied for a quick fix, there is a better solution.

Each time the playground is opened it will be assigned a new container. This means using the normal directory structure you would have to copy the file you want into the new container every time.

Instead, inside the container there is a symbolic link to a Shared Playground Data directory (/Users/UserName/Documents/Shared Playground Data) which remains when reopening the playground, and can be accessed from multiple playgrounds.

You can use XCPlayground to access this shared folder.

import XCPlayground

let path = XCPlaygroundSharedDataDirectoryURL.appendingPathComponent("foo.txt")

The official documentation can be found here: XCPlayground Module Reference

Cool post on how to organize this directory per-playground: Swift, Playgrounds, and XCPlayground


UPDATE: For swift 4.2 use playgroundSharedDataDirectory. Don't need to import anything. Looks like:

let path = playgroundSharedDataDirectory.appendingPathComponent("file")

You can also put your file into your playground's resources. To do this: show Project Navigator with CMD + 1. Drag and drop your file into the resources folder. Then read the file:

On XCode 6.4 and Swift 1.2:

var error: NSError?
let fileURL = NSBundle.mainBundle().URLForResource("Input", withExtension: "txt")
let content = String(contentsOfURL: fileURL!, encoding: NSUTF8StringEncoding, error: &error)

On XCode 7 and Swift 2:

let fileURL = NSBundle.mainBundle().URLForResource("Input", withExtension: "txt")
let content = try String(contentsOfURL: fileURL!, encoding: NSUTF8StringEncoding)

On XCode 8 and Swift 3:

let fileURL = Bundle.main.url(forResource: "Input", withExtension: "txt")
let content = try String(contentsOf: fileURL!, encoding: String.Encoding.utf8)

If the file has binary data, you can use NSData(contentsOfURL: fileURL!) or Data(contentsOf: fileURL!) (for Swift 3).

Tags:

Swift