Fast text file to string array

I was wondering if the simplest and most readable text file in an array of strings is in the quick version.

Text file:

line 1 line 2 line 3 line 4 

To an array like this:

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

I would also like to know how to do similar in structure as follows:

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

so take a text file and put it in a structure in an array.

Thanks for the help!

+6
source share
5 answers

First you should read the file:

 let text = String(contentsOfFile: someFile, encoding: NSUTF8StringEncoding, error: nil) 

Then you split it line by line using the componentsSeparatedByString method:

 let lines : [String] = text.componentsSeparatedByString("\n") 
+6
source

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) } 
+8
source

Here is a way to convert a string to an array (after reading in the text):

 var myString = "Here is my string" var myArray : [String] = myString.componentsSeparatedByString(" ") 

Returns an array of strings with the following values: ["Here", "is", "my", "string"]

+2
source

In Swift 3 it worked for me as shown below:

 Import Foundation let lines : [String] = contents.components(separatedBy: "\n") 
0
source

Updated for Swift 4:

 do { let file = try String(contentsOfFile: path!) let text: [String] = file.components(separatedBy: "\n") } catch { Swift.print("Fatal Error: Couldn't read the contents!") } 
-1
source

Source: https://habr.com/ru/post/984148/


All Articles