[英]Swift 2.0 code works in Xcode but not in Playground
我正在學習Swift並且一直在試圖弄清楚我無法加載文件。 事實證明,代碼在Xcode中工作,但在操場上不起作用。 這是什么原因?
這是代碼:
func testFileLoad(){
let myFilePath: String = "/Users/clay/Desktop/test.txt"
let t: Bool = NSFileManager.defaultManager().fileExistsAtPath(myFilePath)
print(t)
let s: String = try! String(contentsOfFile: myFilePath, encoding: NSUTF8StringEncoding)
print(s)
do {
let p: String = try String(contentsOfFile: myFilePath, encoding: NSUTF8StringEncoding)
print(p)
} catch {
print("nope")
}
}
在Xcode的測試模塊中運行,它可以正常工作並打印我希望的控制台。
Test Suite 'Selected tests' started at 2015-08-05 14:24:15.977
Test Suite 'swiftgraphTests' started at 2015-08-05 14:24:15.978
Test Case '-[swiftgraphTests.swiftgraphTests testFileLoad]' started.
true
this is a test
this is a test
Test Case '-[swiftgraphTests.swiftgraphTests testFileLoad]' passed (0.001 seconds).
Test Suite 'swiftgraphTests' passed at 2015-08-05 14:24:15.979.
Executed 1 test, with 0 failures (0 unexpected) in 0.001 (0.001) seconds
Test Suite 'Selected tests' passed at 2015-08-05 14:24:15.979.
Executed 1 test, with 0 failures (0 unexpected) in 0.001 (0.002) seconds
在操場上,我明白了:
我在這做錯了什么? 我不正確地使用操場嗎?
如果你去菜單
“查看” - >“調試區” - >“顯示調試區”
您將看到完整錯誤:“您無權從Playground *訪問文件系統。”
解決方法是使用Project Navigator將文件包含在Playground中。
轉到菜單
“查看” - >“導航器” - >“顯示項目導航器”
然后將文件拖放到“Resources”文件夾中。
然后使用NSBundle獲取路徑。
func testFileLoad() {
// get the file path for the file from the Playground's Resources folder
guard let path = NSBundle.mainBundle().pathForResource("test", ofType: "txt") else {
print("Oops, the file is not in the Playground")
return
}
// keeping the examples from your question
let s: String = try! String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
print(s)
do {
let p: String = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
print(p)
} catch {
print("nope")
}
}
testFileLoad()
*實際上,您只能訪問包含Playground共享數據的/var/
文件夾,而Playground只提供快捷方式。 Playground導航器中的此文件夾實際上代表/var/
文件夾,並且對於每個Playground都是唯一的。 您可以使用NSBundle查看其地址:
NSBundle.mainBundle().resourcePath
可能是一個許可問題。 可能在您的XCode項目中,您有一組在操場上不可用的權限。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.