Swift 2.0 code works in Xcode but not in Playground

后端 未结 2 714
不思量自难忘°
不思量自难忘° 2021-01-05 17:36

I\'m learning Swift and have been frustrated trying to figure out how I\'m unable to load files. It turns out that the code works in Xcode but does not work in a playground.

相关标签:
2条回答
  • 2021-01-05 18:14

    Might be a permission problem. Probably in your XCode project you have a set of privileges which are not available in playground.

    0 讨论(0)
  • 2021-01-05 18:35

    If you go to the menu

    "View" -> "Debug Area" -> "Show Debug Area"

    you will see the full error: "you don't have permissions to access the filesystem from the Playground*."

    The workaround is to include the file in the Playground using its Project Navigator.

    Go to the menu

    "View" -> "Navigators" -> "Show Project Navigator"

    then drag and drop your file into the "Resources" folder.

    Then use NSBundle to get the path.

    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()
    

    *Actually you have only access to the /var/ folder containing your Playground shared data, and the Playground is just offering a shortcut. This folder in the Playground's navigator actually represents the /var/ folder, and is unique for each Playground. You can see its address with NSBundle:

    NSBundle.mainBundle().resourcePath
    
    0 讨论(0)
提交回复
热议问题