Swift 2.0代码适用于Xcode,但不适用于Playground

前端之家收集整理的这篇文章主要介绍了Swift 2.0代码适用于Xcode,但不适用于Playground前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在学习 Swift并且一直在试图弄清楚我无法加载文件.事实证明,代码在Xcode中工作,但在操场上不起作用.这是什么原因?

这是代码

  1. func testFileLoad(){
  2. let myFilePath: String = "/Users/clay/Desktop/test.txt"
  3. let t: Bool = NSFileManager.defaultManager().fileExistsAtPath(myFilePath)
  4. print(t)
  5.  
  6. let s: String = try! String(contentsOfFile: myFilePath,encoding: NSUTF8StringEncoding)
  7. print(s)
  8.  
  9. do {
  10. let p: String = try String(contentsOfFile: myFilePath,encoding: NSUTF8StringEncoding)
  11. print(p)
  12. } catch {
  13. print("nope")
  14. }
  15. }

在Xcode的测试模块中运行,它可以正常工作并打印我希望的控制台.

  1. Test Suite 'Selected tests' started at 2015-08-05 14:24:15.977
  2. Test Suite 'swiftgraphTests' started at 2015-08-05 14:24:15.978
  3. Test Case '-[swiftgraphTests.swiftgraphTests testFileLoad]' started.
  4. true
  5. this is a test
  6. this is a test
  7. Test Case '-[swiftgraphTests.swiftgraphTests testFileLoad]' passed (0.001 seconds).
  8. Test Suite 'swiftgraphTests' passed at 2015-08-05 14:24:15.979.
  9. Executed 1 test,with 0 failures (0 unexpected) in 0.001 (0.001) seconds
  10. Test Suite 'Selected tests' passed at 2015-08-05 14:24:15.979.
  11. Executed 1 test,with 0 failures (0 unexpected) in 0.001 (0.002) seconds

在操场上,我明白了:

我在这做错了什么?我不正确地使用操场吗?

如果你去菜单

“View” -> “Debug Area” -> “Show Debug Area”

您将看到完整错误:“您无权从Playground *访问文件系统.”

解决方法是使用Project Navigator将文件包含在Playground中.

转到菜单

“View” -> “Navigators” -> “Show Project Navigator”

然后将文件拖放到“Resources”文件夹中.

然后使用NSBundle获取路径.

  1. func testFileLoad() {
  2.  
  3. // get the file path for the file from the Playground's Resources folder
  4. guard let path = NSBundle.mainBundle().pathForResource("test",ofType: "txt") else {
  5. print("Oops,the file is not in the Playground")
  6. return
  7. }
  8.  
  9. // keeping the examples from your question
  10. let s: String = try! String(contentsOfFile: path,encoding: NSUTF8StringEncoding)
  11. print(s)
  12.  
  13. do {
  14. let p: String = try String(contentsOfFile: path,encoding: NSUTF8StringEncoding)
  15. print(p)
  16. } catch {
  17. print("nope")
  18. }
  19.  
  20. }
  21.  
  22. testFileLoad()

*实际上,您只能访问包含Playground共享数据的/ var /文件夹,而Playground只提供快捷方式. Playground导航器中的此文件夹实际上代表/ var /文件夹,并且对于每个Playground都是唯一的.您可以使用NSBundle查看其地址:

  1. NSBundle.mainBundle().resourcePath

猜你在找的Swift相关文章