描述的答案:
首先,您需要过滤数组以仅获取步骤;根据发布的parent 数组,有效步骤似乎应该包含一个键为“Step”和一个格式为“S #”的值,因此可以将其过滤为:
let filtered = parent.filter { (currentDict) -> Bool in
// get the value for key "Step"
guard let value = currentDict["Step"] else {
return false
}
// check ifthe value matches the "S #"
let trimmingBySpace = value.components(separatedBy: " ")
if trimmingBySpace.count != 2 || trimmingBySpace[0] != "S" || Int(trimmingBySpace[1]) == nil {
return false
}
return true
}
到目前为止会得到:
[["Step": "S 3", "Desc": "Do third step"],
["Step": "S 1", "Desc": "Do first step"],
["Step": "S 2", "Desc": "Do second step"]]
其次,您将按“Step”键的值对filtered数组进行排序:
let sorted = filtered.sorted { $0["Step"]! < $1["Step"]! }
你应该得到:
[["Step": "S 1", "Desc": "Do first step"],
["Step": "S 2", "Desc": "Do second step"],
["Step": "S 3", "Desc": "Do third step"]]
最后,您将映射sorted 数组以获取描述值:
let descriptions = sorted.map { $0["Desc"] ?? "" }
descriptions 应该是:
["Do first step", "Do second step", "Do third step"]
一步到位:
let result = parent.filter { (currentDict) -> Bool in
// get the value for key "Step"
guard let value = currentDict["Step"] else {
return false
}
// check ifthe value matches the "S #"
let trimmingBySpace = value.components(separatedBy: " ")
if trimmingBySpace.count != 2 || trimmingBySpace[0] != "S" || Int(trimmingBySpace[1]) == nil {
return false
}
return true
}.sorted {
$0["Step"]! < $1["Step"]!
}.map {
$0["Desc"] ?? ""
}
print(result) // ["Do first step", "Do second step", "Do third step"]