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
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)
}