我正在尝试解析包含以下格式数据的 .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/