How can I read a file in a swift playground

后端 未结 9 1839
时光说笑
时光说笑 2020-12-12 22:37

Im trying to read a text file using a Swift playground with the following

let dirs : String[]? =    NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory         


        
9条回答
  •  时光取名叫无心
    2020-12-12 22:59

    While the answer has been supplied for a quick fix, there is a better solution.

    Each time the playground is opened it will be assigned a new container. This means using the normal directory structure you would have to copy the file you want into the new container every time.

    Instead, inside the container there is a symbolic link to a Shared Playground Data directory (/Users/UserName/Documents/Shared Playground Data) which remains when reopening the playground, and can be accessed from multiple playgrounds.

    You can use XCPlayground to access this shared folder.

    import XCPlayground
    
    let path = XCPlaygroundSharedDataDirectoryURL.appendingPathComponent("foo.txt")
    

    The official documentation can be found here: XCPlayground Module Reference

    Cool post on how to organize this directory per-playground: Swift, Playgrounds, and XCPlayground


    UPDATE: For swift 4.2 use playgroundSharedDataDirectory. Don't need to import anything. Looks like:

    let path = playgroundSharedDataDirectory.appendingPathComponent("file")
    

提交回复
热议问题