Can not make path to the file in Swift

亡梦爱人 提交于 2019-12-22 12:30:16

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/25626896/can-not-make-path-to-the-file-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!