Greg Greg - 3 months ago 20
Swift Question

How can I read a file in a swift playground

Im trying to read a text file using a Swift playground with the following

let dirs : String[]? = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) as? String[]

if (dirs != nil) {
let directories:String[] = dirs!;
let dir = directories[0]; //documents directory
let path = dir.stringByAppendingPathComponent(file);

//read
let content = String.stringWithContentsOfFile(path, encoding: NSUTF8StringEncoding, error: nil)
}


However this fails with no error. It seems the first line stops the playground from outputting anything below

Answer

This works for me. The only thing I changed was to be explicit about the file name (which is implied in your example) - perhaps you have a typo in the off-screen definition of the "file" variable?

let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) as? [String]

let file = "trial.txt" // My change to your code - yours is presumably set off-screen
if let directories = dirs {
  let dir = directories[0]; //documents directory
  let path = dir.stringByAppendingPathComponent(file);

  //read
  let content = NSString(contentsOfFile: path, usedEncoding: nil, error: nil)
  // works...
}
Comments