Ios 试图在Swift中将txt文件的内容解析到字典中

Ios 试图在Swift中将txt文件的内容解析到字典中,ios,swift,csv,nsdictionary,Ios,Swift,Csv,Nsdictionary,我正在尝试解析包含以下格式数据的.txt文件的内容: 93 --- Afghanistan 355 --- Albania 213 --- Algeria 684 --- American Samoa 376 --- Andorra 244 --- Angola ... 1 670 --- North Mariana Islands (Saipan) ... 仅供参考,这些是不同国家的区号 我需要使用Swift读取数据,并将其放入字典,其中键是国家名称,值是区号 这是迄今为止我所掌握的代码:

我正在尝试解析包含以下格式数据的.txt文件的内容:

93 --- Afghanistan
355 --- Albania
213 --- Algeria
684 --- American Samoa
376 --- Andorra
244 --- Angola
...
1 670 --- North Mariana Islands (Saipan)
...
仅供参考,这些是不同国家的区号

我需要使用Swift读取数据,并将其放入字典,其中键是国家名称,值是区号

这是迄今为止我所掌握的代码:

class ViewController: UIViewController {

    var dataArray:[String]?

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

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


        }
    }

}

目前,我只知道如何读入每一行,但我想做的是,当我读入每一行时,将第一个字符串作为值添加到字典中,并将(---)后面出现的第二个字符串作为键。有人有什么建议吗?

可以尝试类似的方法,但尚未测试代码,因此可能需要一些调整

var dictionary = [String: String]()

for line in dataArray {

    var components = line.components(separatedBy: " --- ")

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

我不得不将接受答案的第三行改为

var components = line.components(separatedBy: " --- ")

非常感谢您的回复。我试图运行您的代码,但出现以下错误:致命错误:在最后一行上展开可选值时意外发现nil:dictionary[Int(components[0])!]=components[1]嗯,在那一行上放一个断点,看看
组件中有什么值
似乎是因为某种原因,里面有一个
nil
。还要确保在文本文件中,所有的区号实际上都是数字。。否则,您将不得不再次使用stringsThanks。问题是,在我的txt文件中,有一些区号是这样的:1670--北马里亚纳群岛(塞班岛),这就是造成问题的原因。建议?啊,是的,它不会解析为int,然后可以使用字符串,我会更改我的答案