Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

swift

How do I load a text file line by line into an array with swift?

like image 709
Sebastian Krogull Avatar asked Jun 04 '14 14:06

Sebastian Krogull


People also ask

How do I convert a string to an array in Swift?

To convert a string to an array, we can use the Array() intializer syntax in Swift. Here is an example, that splits the following string into an array of individual characters. Similarly, we can also use the map() function to convert it. The map() function iterates each character in a string.


1 Answers

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.

like image 147
Cezar Avatar answered Oct 14 '22 09:10

Cezar