Swift Text File To Array of Strings

后端 未结 6 1365
逝去的感伤
逝去的感伤 2021-01-01 22:20

I was wondering what the simplest and cleanest to read a text file into an array of strings is in swift.

Text file:

line 1
line 2
line 3 
line 4
         


        
6条回答
  •  自闭症患者
    2021-01-01 22:46

    Updated for Swift 5:

    The const path contains the file path.

    do {
        let path: String = "file.txt"
        let file = try String(contentsOfFile: path)
        let text: [String] = file.components(separatedBy: "\n")
    } catch let error {
        Swift.print("Fatal Error: \(error.localizedDescription)")
    }
    

    If you want to print what's inside of file.txt line by line:

    for line in text {
        Swift.print(line)
    }
    

提交回复
热议问题