syedfa syedfa - 3 months ago 6x
iOS Question

Trying to parse contents of txt file into a Dictionary in Swift

Dear fellow iOS developers:

I am trying to parse the contents of a .txt file that contains the following data in this format:

93 --- Afghanistan
355 --- Albania
213 --- Algeria
684 --- American Samoa
376 --- Andorra
244 --- Angola
1 670 --- North Mariana Islands (Saipan)

FYI, these are area codes for different countries.

I need to read the data using Swift, and put it into a Dictionary, where the keys are country names, and the values are the area codes.

This is the code that I have thus far:

class ViewController: UIViewController {

var dataArray:[String]?

override func viewDidLoad() {
// Do any additional setup after loading the view, typically from a nib.

func loadCountryCodes() {
// Specify the path to the countries list file.
let pathToFile = NSBundle.mainBundle().pathForResource("countrycodes", ofType: "txt")

if let path = pathToFile {
// Load the file contents as a string.
let countriesString = try! String(contentsOfFile: path, encoding: NSUTF8StringEncoding)

// Append the countries from the string to the dataArray array by breaking them using the line change character.
dataArray = countriesString.componentsSeparatedByString("\n")



At the moment, I only know how to read each line in, but what I would like to do, is as I read each line in, add the first string to the dictionary as a value, and the second string that appears after the (---) as the key. Does anyone have any suggestions?

Thanks in advance to all who reply.
Between the area code


Can try something like this, haven't tested the code though so might need some tweaking

var dictionary = [String: String]()

for line in dataArray {

    var components = line.componentsSeparatedByString(" --- ")

    dictionary[components[0]] = components[1]