我有各种文本文件,其中每一行都包含 string-key=string-value
我可以将文件读入字符串(或者可能是一个数组),逐行检查并自己拆分成键/值对,但是,我想知道我是否缺少一些内置或更简单的“快速”方式这样做(swift 的新手)
我找不到之前讨论过的这个问题
最佳答案
核心概念仍然依赖于 componentsSeparatedByString
,但您可以通过使用像 reduce
这样的高阶函数让它看起来更“敏捷”:
let fileContent = try! NSString(contentsOfFile: "/path/to/file.txt", encoding: NSUTF8StringEncoding)
let result = fileContent.componentsSeparatedByString("\n")
.reduce([String: String]()) { (var dict, line) in
let components = line.componentsSeparatedByString("=")
dict[components[0]] = components[1]
return dict
}
它的作用是:按行拆分文件的内容,以一个空的[String: String]
开始,循环遍历每一行,将其拆分并将键值分配给字典。
关于ios - Swift ios - 将 key=value 文本文件读入 nsdictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34615464/