How do I load a text file line by line into an array
with swift
?
This works only until Xcode 6.1 beta 1. In 6.1 beta 2 you must write this:
var err: NSError? = NSError()
let s = String(contentsOfFile: fullPath, encoding: NSUTF8StringEncoding, error: &err)
Where fullPath
is a string containing the full path to the file and NSUTF8StringEncoding
is a predefined constant for UTF8-Encoding.
You can also use NSMacOSRomanStringEncoding
for Mac files or NSISOLatin1StringEncoding
for Windows files.
s
is an optional String and you can look if reading the file was successful:
if (s != nil)
{
return (s!) // Return the string as "normal" string, not as optional string
}
Something along the lines of:
func arrayFromContentsOfFileWithName(fileName: String) -> [String]? {
guard let path = NSBundle.mainBundle().pathForResource(fileName, ofType: "txt") else {
return nil
}
do {
let content = try String(contentsOfFile:path, encoding: NSUTF8StringEncoding)
return content.componentsSeparatedByString("\n")
} catch _ as NSError {
return nil
}
}
This approach assumes the file in question is located in your app bundle.
If you are in Swift 2.0, you should use:
let path = NSBundle.mainBundle().pathForResource(fileName, ofType: nil)
if path == nil {
return nil
}
var fileContents: String? = nil
do {
fileContents = try String(contentsOfFile: path!, encoding: NSUTF8StringEncoding)
} catch _ as NSError {
return nil
}