2

In the playground (Xcode 7, Swift 2.1) for OSX, this creates nothing but an empty string:

let fileString = "/Users/me/file.txt"
var text = try NSString( contentsOfFile: fileString, encoding: NSUTF8StringEncoding )

What am I doing wrong?

$ cat /Users/me/file.txt

in the Terminal confirms that the file contains ASCII content.

Thanks in advance!

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Dribbler
  • 4,343
  • 10
  • 33
  • 53

1 Answers1

2

Basically a Playground is sandboxed and has no access to the file system.

To play with files you have to add them to the Resources folder of the Playground and access them with

NSBundle.mainBundle().pathForResource("file", ofType: "txt")

It's always recommended to wrap a try statement in a do - catch block and catch the error.

Update:

For example

let url = NSBundle.mainBundle().URLForResource( "file", withExtension: "txt")!
do { 
  let text = try NSString( contentsOfURL: url, encoding: NSUTF8StringEncoding) 
} catch let errOpening as NSError { 
  print("Error!", errOpening) 
}
Dribbler
  • 4,343
  • 10
  • 33
  • 53
vadian
  • 274,689
  • 30
  • 353
  • 361