Read and write a String from text file

前端 未结 21 1416
别跟我提以往
别跟我提以往 2020-11-22 00:02

I need to read and write data to/from a text file, but I haven\'t been able to figure out how.

I found this sample code in the Swift\'s iBook, but I still don\'t kno

21条回答
  •  甜味超标
    2020-11-22 00:34

    Xcode 8, Swift 3 way to read file from the app bundle:

    if let path = Bundle.main.path(forResource: filename, ofType: nil) {
        do {
            let text = try String(contentsOfFile: path, encoding: String.Encoding.utf8)
            print(text)
        } catch {
            printError("Failed to read text from \(filename)")
        }
    } else {
        printError("Failed to load file from app bundle \(filename)")
    } 
    

    Here's a convenient copy and paste Extension

    public extension String {
        func contentsOrBlank()->String {
            if let path = Bundle.main.path(forResource:self , ofType: nil) {
                do {
                    let text = try String(contentsOfFile:path, encoding: String.Encoding.utf8)
                    return text
                    } catch { print("Failed to read text from bundle file \(self)") }
            } else { print("Failed to load file from bundle \(self)") }
            return ""
        }
        }
    

    For example

    let t = "yourFile.txt".contentsOrBlank()
    

    You almost always want an array of lines:

    let r:[String] = "yourFile.txt"
         .contentsOrBlank()
         .characters
         .split(separator: "\n", omittingEmptySubsequences:ignore)
         .map(String.init)
    

提交回复
热议问题