Search code examples
macosswiftnsbundle

Can not make path to the file in Swift


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?


Solution

  • 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