Im trying to read a text file using a Swift playground with the following
let dirs : String[]? = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory
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).