ios - 快速过滤和排序字典数组

标签 ios swift filter swift4

我有以下数组:

let parent = [ ["Step":"S 3", "Desc":"Do third step" ],
               ["Step":"S 1", "Desc":"Do first step" ],
               ["Step":"S 2", "Desc":"Do second step" ],
                ["Step":"P 1", "Desc":"Some other thing" ] ]

如何以尽可能少的步骤对数组进行过滤和排序(使用过滤和排序函数),以便获得以下输出字符串或标签 --

1.做第一步

2.做第二步

3.做第三步

最佳答案

我建议过滤、排序、枚举、映射和连接:

let results = parent
    .filter { $0["Step"]?.first == "S" }
    .sorted { $0["Step"]!.compare($1["Step"]!, options: .numeric) == .orderedAscending }
    .enumerated()
    .map { (index, value) in "\(index + 1). \(value["Desc"]!)" }
    .joined(separator: "\n")

一个关键的考虑因素是使用 .numeric 比较,这样“S 10”就会出现在“S 9”之后,而不是在“S 1”和“S 2”之间。如果要在字符串中嵌入数值,您不想进行简单的字符串比较。

我还加入了那个枚举,因为如果你删除了一个项目,你可能想确保你的列表中的数字不会仅仅因为你的 Step 中的特定编码而跳过一个值> 字符串。


不相关,字典对于这样的事情来说是一个糟糕的模型。我建议使用自定义类型:

struct Task {
    enum TaskType {
        case step
        case process    // or whatever "P" is supposed to stand for
    }

    let sequence: Int
    let type: TaskType
    let taskDescription: String
}

let parent = [Task(sequence: 3, type: .step, taskDescription: "Do third step"),
              Task(sequence: 1, type: .step, taskDescription: "Do first step"),
              Task(sequence: 2, type: .step, taskDescription: "Do second step"),
              Task(sequence: 3, type: .process, taskDescription: "Some other thing")]

let results = parent
    .filter { $0.type == .step }
    .sorted { $0.sequence < $1.sequence }
    .map { "\($0.sequence). \($0.taskDescription)" }
    .joined(separator: "\n")

关于ios - 快速过滤和排序字典数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49802692/

相关文章:

ios - 错误域=NSCocoaErrorDomain 代码=3840 "No string key for value in object around character 1."

iphone - xcode - 使搜索栏出现/消失

ios - 将数据从一个 View Controller 传递到另一个 View Controller

regex - Scala Spark 使用子字符串和字符过滤 DataFrame 中的行

sql - 将 or-filter 更改为 and-filter 用于连接表的 `column = ANY()` 比较

python - 基于多个条件对 DataFrame 进行切片

ios - 获取 CoreData 中保存的 NSData 的 URL

ios - SwiftUI:onDismiss 没有被调用

View 加载前的 Swift 观察者

ios - 如果 UITabBar 的项目超过 5 个,则操作不起作用