Swift Text File To Array of Strings

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

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

Tags:

String

File

Swift