我正在解析20世纪70年代的文本文件(最初来自CDC 6600),该文件包含具有可变数量参数的行。以下是一些样本...
GW 1 5 0.0000 -1.0000 0.0000000 0.00000 1.0000 0.000 .00667
GE 1
FR 0 0 0 0 46.29 0.
我正在使用split
(yay,最终在Xcode 7中修复!)将其分解为一个数组,然后将非零值插入到字典中,就像这样......
let parts: [String] = original!.characters.split{ $0 == " " || $0 == "," }.map{ String($0).trim() }
if parts.count > 1 { data["I1"] = parts[1] }
if parts.count > 2 { data["I2"] = parts[2] }
if parts.count > 3 { data["F1"] = parts[3] }
最后,我理智地检查输入,因为我已经看到了许多不正确文件的例子。所以我有一系列这样的功能......
func checkGA() {
if (data["I1"] == "" || data["I2"] == "" || data["F1"] == "" || data["F2"] == "" || data["F3"] == "" || data["F4"] == "") { problem = "Missing parameters." }
if (data["F5"] != "" || data["F6"] != "" || data["F7"] != "") { problem = "Extra paramters after F4." }
}
我觉得在Swift中检查这些输入的方法可能不那么难看。我在想,也许我可以在地图或类似地方使用范围运算符?有点像:
if (data["F2"..."F4"] != "") ...
但是这种函数式编程对我来说是非常新的。任何大师都有建议吗?
答案 0 :(得分:1)
您可以考虑使用错误处理:
enum FieldError : ErrorType {
case MissingField(String)
case ExtraField(String,String)
}
do {
// sample data
let data = ["I1": "hello", "I2": "world", "F1":"Greetings" ]
try ["I1", "I2", "F1"].forEach { key in
guard let value = data[key] where value != "" else {
throw FieldError.MissingField(key)
}
}
try ["F5", "F6", "F7", "F8"].forEach { key in
if let value = data[key] where value != "" {
throw FieldError.ExtraField(key, value)
}
}
print("All data tests passed")
}
catch FieldError.MissingField(let key) {
print("Missing field for key: \(key)")
}
catch let FieldError.ExtraField(key, value) {
print("Extra field with key: \(key), value: \(value)")
}