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
Swift 4:
do {
let contents = try String(contentsOfFile: file, encoding: String.Encoding.utf8)
let lines : [String] = contents.components(separatedBy: "\n")
} catch let error as NSError {
print(error.localizedDescription)
}
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)
}
Updated for Swift 3
var arrayOfStrings: [String]?
do {
// This solution assumes you've got the file in your bundle
if let path = Bundle.main.path(forResource: "YourTextFilename", ofType: "txt"){
let data = try String(contentsOfFile:path, encoding: String.Encoding.utf8)
arrayOfStrings = data.components(separatedBy: "\n")
print(arrayOfStrings)
}
} catch let err as NSError {
// do something with Error
print(err)
}
Here is a way to convert a string to an array(Once you read in the text):
var myString = "Here is my string"
var myArray : [String] = myString.componentsSeparatedByString(" ")
This returns a string array with the following values: ["Here", "is", "my", "string"]
In Swift 3 for me worked like below:
Import Foundation
let lines : [String] = contents.components(separatedBy: "\n")
First you must read the file:
let text = String(contentsOfFile: someFile, encoding: NSUTF8StringEncoding, error: nil)
Then you separate it by line using the componentsSeparatedByString
method:
let lines : [String] = text.componentsSeparatedByString("\n")