ios - 试图将 txt 文件的内容解析为 Swift 中的字典

标签 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 读取数据,并将其放入字典中,其中键是国家名称,值是区号。

这是我到目前为止的代码:

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]
}

关于ios - 试图将 txt 文件的内容解析为 Swift 中的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38066679/

相关文章:

ios - 是否可以通过编程方式更改 iOS 设备的时间

ios - 在 UITextView 中更改变量

ios - Swift - UIImageView 缩放比 UIScrollView 大

ios - 相同的表达式在 Objective-C 和 Swift 中返回不同的值

node.js - 如何从 Node.js 程序运行 Excel VBA?

ios - Swift UITableview 自定义单元格 Imageview 颜色更改在另一个函数中

ios - Iphone X 自定义导航支持,标签栏尺寸

python - Pandas 合并错误TypeError : '>' not supported between instances of 'int' and 'str'

Swift:在switch中初始化后获取子类变量

r - 如何使用 R 将 csv 转换为 xls?