How can I read a file in a swift playground

后端 未结 9 1844
时光说笑
时光说笑 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 23:05

    Swift 3 (Xcode 8)

    The code below works in both iOS and macOS playgrounds. The text file ("MyText.txt" in this example) must be in the Resources directory of the playground. (Note: You may need to open the navigator window to see the directory structure of your playground.)

    import Foundation
    
    if let fileURL = Bundle.main.url(forResource:"MyText", withExtension: "txt")
    {
        do {
            let contents = try String(contentsOf: fileURL, encoding: String.Encoding.utf8)
            print(contents)
        } catch {
            print("Error: \(error.localizedDescription)")
        }
    } else {
        print("No such file URL.")
    }
    

提交回复
热议问题