Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read a file in a swift playground

Tags:

swift

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

like image 679
Greg Avatar asked Jun 16 '14 14:06

Greg


People also ask

How do I open a swift playground file?

playground file. Open Utility inspector, In the playground press opt-cmd-1 to open the File Inspector. You should see the playground on the right. If you don't have it selected, press cmd-1 to open the Project Navigator and click on the playground file.

What is the difference between playground and Xcode?

An Xcode project allows you to create real apps that you could eventually upload to the App Store (providing you became an Apple Developer). An Xcode Playground allows you to play with code and test it out. It isn't for mainstream developing.


1 Answers

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).

like image 104
knshn Avatar answered Oct 06 '22 23:10

knshn