Sebastian Krogull Sebastian Krogull - 5 months ago 32
Swift Question

How do I load a text file into an array with Swift?

How do I load a text file into an

array
with
swift
?

Answer

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.