无法在Swift中创建文件的路径

tse*_*tse 2 macos nsbundle swift

我尝试在Swift中打开文件.为此,我创建了文件路径.它不起作用.

maaaacy:~ $ pwd
/Users/tsypa
maaaacy:~ $ cat a.txt
test
maaaacy:~ $ ./a.swift 
nil!
maaaacy:~ $ 
Run Code Online (Sandbox Code Playgroud)

剧本:

#!/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!")
}
Run Code Online (Sandbox Code Playgroud)

怎么了?

aka*_*kyy 6

使用Swift REPL时,NSBundle.mainBundle()路径实际指向:

/Applications/Xcode6-Beta6.app/Contents/SharedFrameworks/LLDB.framework/Versions/A/Resources
Run Code Online (Sandbox Code Playgroud)

您可能必须使用NSFileManager:

let manager = NSFileManager.defaultManager()

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

注意:您实际上可以自动扩展路径中的波浪号以避免硬编码整个用户的主路径:

"~/a.txt".stringByExpandingTildeInPath // prints /Users/<your user>/a.txt
Run Code Online (Sandbox Code Playgroud)