Unable to create file path in Swift

I am trying to open a file in Swift. To do this, I create a file path. This does not work.

maaaacy:~ $ pwd /Users/tsypa maaaacy:~ $ cat a.txt test maaaacy:~ $ ./a.swift nil! maaaacy:~ $ 

script:

 #!/usr/bin/xcrun swift import Foundation var filePath = NSBundle.mainBundle().pathForResource("a", ofType: "txt", inDirectory: "/Users/tsypa") if let file = filePath { println("file path \(file)") // reading content of the file will be here } else { println("nil!") } 

What's wrong?

+2
source share
1 answer

When using Swift REPL, the NSBundle.mainBundle() path actually points to:

 /Applications/Xcode6-Beta6.app/Contents/SharedFrameworks/LLDB.framework/Versions/A/Resources 

You may need to use NSFileManager :

 let manager = NSFileManager.defaultManager() if manager.fileExistsAtPath("/Users/tsypa/a.txt") { // file exists, read } else { // file doesn't exist } 

Note. . In fact, you automatically expand the tilde along the way to avoid hard coding the user's full home path:

 "~/a.txt".stringByExpandingTildeInPath // prints /Users/<your user>/a.txt 
+6
source

All Articles