我尝试在Swift中打开文件。为此,我创建了文件路径。它不起作用。
maaaacy:~ $ pwd
/Users/tsypa
maaaacy:~ $ cat a.txt
test
maaaacy:~ $ ./a.swift
nil!
maaaacy:~ $
剧本:
#!/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!")
}
怎么了?
答案 0 :(得分:6)
使用Swift REPL时,NSBundle.mainBundle()
的路径实际上指向:
/Applications/Xcode6-Beta6.app/Contents/SharedFrameworks/LLDB.framework/Versions/A/Resources
您可能需要使用NSFileManager代替:
let manager = NSFileManager.defaultManager()
if manager.fileExistsAtPath("/Users/tsypa/a.txt") {
// file exists, read
} else {
// file doesn't exist
}
注意:您实际上可以自动扩展路径中的波浪号,以避免硬编码整个用户的主路径:
"~/a.txt".stringByExpandingTildeInPath // prints /Users/<your user>/a.txt