Henry oscannlain-miller Henry oscannlain-miller - 11 months ago 79
Swift Question

Swift Text File To Array of Strings

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!

Ian Ian

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