How can I read a file in a swift playground

后端 未结 9 1840
时光说笑
时光说笑 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:46

    You can also put your file into your playground's resources. To do this: show Project Navigator with CMD + 1. Drag and drop your file into the resources folder. Then read the file:

    On XCode 6.4 and Swift 1.2:

    var error: NSError?
    let fileURL = NSBundle.mainBundle().URLForResource("Input", withExtension: "txt")
    let content = String(contentsOfURL: fileURL!, encoding: NSUTF8StringEncoding, error: &error)
    

    On XCode 7 and Swift 2:

    let fileURL = NSBundle.mainBundle().URLForResource("Input", withExtension: "txt")
    let content = try String(contentsOfURL: fileURL!, encoding: NSUTF8StringEncoding)
    

    On XCode 8 and Swift 3:

    let fileURL = Bundle.main.url(forResource: "Input", withExtension: "txt")
    let content = try String(contentsOf: fileURL!, encoding: String.Encoding.utf8)
    

    If the file has binary data, you can use NSData(contentsOfURL: fileURL!) or Data(contentsOf: fileURL!) (for Swift 3).

提交回复
热议问题