How do I load a text file line by line into an array
with 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With