加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 05:38:21 所属栏目:百科 来源:网络整理
导读:我正在学习 Swift并且一直在试图弄清楚我无法加载文件.事实证明,代码在Xcode中工作,但在操场上不起作用.这是什么原因? 这是代码: func testFileLoad(){ let myFilePath: String = "/Users/clay/Desktop/test.txt" let t: Bool = NSFileManager.defaultMana
我正在学习 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

在操场上,我明白了:

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

如果你去菜单

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

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

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

转到菜单

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

然后将文件拖放到“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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读