2

I try to open the file in Swift. For it I create the file path. It doesn't work.

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

The 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?

akashivskyy
  • 44,342
  • 16
  • 106
  • 116
tse
  • 5,769
  • 6
  • 38
  • 58
  • The problem is that the file doesn't belong to a 'bundle'. Use an [`NSFileManager`](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html) instead (or `NSURL` if you only require a reference to the path of the resource). – Alladinian Sep 02 '14 at 15:24

1 Answers1

6

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

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

You may have to use NSFileManager instead:

let manager = NSFileManager.defaultManager()

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

Note: You can actually automatically expand tilde in the path to avoid hardcoding the full user's home path:

"~/a.txt".stringByExpandingTildeInPath // prints /Users/<your user>/a.txt
akashivskyy
  • 44,342
  • 16
  • 106
  • 116