Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Text File To Array of Strings

Tags:

string

file

swift

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

Into an array like this:

var array = ["line 1","line 2","line 3","line 4"]

I would also like to know how to do a similar thing into struct like this:

Struct struct{
   var name: String!
   var email: String!
}

so take a text file and put it into struct's in an array.

Thanks for the help!

like image 284
Henry oscannlain-miller Avatar asked Mar 23 '15 18:03

Henry oscannlain-miller


2 Answers

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)
    }
like image 124
Adrian Avatar answered Sep 22 '22 12:09

Adrian


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")
like image 44
Ian Avatar answered Sep 21 '22 12:09

Ian