I\'m learning Swift and have been frustrated trying to figure out how I\'m unable to load files. It turns out that the code works in Xcode but does not work in a playground.
Might be a permission problem. Probably in your XCode project you have a set of privileges which are not available in playground.
If you go to the menu
"View" -> "Debug Area" -> "Show Debug Area"
you will see the full error: "you don't have permissions to access the filesystem from the Playground*."
The workaround is to include the file in the Playground using its Project Navigator.
Go to the menu
"View" -> "Navigators" -> "Show Project Navigator"
then drag and drop your file into the "Resources" folder.
Then use NSBundle to get the path.
func testFileLoad() {
// get the file path for the file from the Playground's Resources folder
guard let path = NSBundle.mainBundle().pathForResource("test", ofType: "txt") else {
print("Oops, the file is not in the Playground")
return
}
// keeping the examples from your question
let s: String = try! String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
print(s)
do {
let p: String = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
print(p)
} catch {
print("nope")
}
}
testFileLoad()
*Actually you have only access to the /var/
folder containing your Playground shared data, and the Playground is just offering a shortcut. This folder in the Playground's navigator actually represents the /var/
folder, and is unique for each Playground. You can see its address with NSBundle:
NSBundle.mainBundle().resourcePath