You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift字典数组的过滤与排序:如何快速生成指定格式输出?

Swift数组过滤+排序+格式化解决方案

没问题,咱们用Swift的filter、sorted配合链式调用,几步就能搞定这个需求,代码简洁又易读:

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" ] ]

// 一步完成过滤、排序、格式化、拼接
let result = parent
    // 1. 过滤出以"S "开头的Step项
    .filter { $0["Step"]?.hasPrefix("S ") == true }
    // 2. 按Step里的数字升序排序
    .sorted {
        guard let num1 = Int($0["Step"]?.replacingOccurrences(of: "S ", with: "") ?? ""),
              let num2 = Int($1["Step"]?.replacingOccurrences(of: "S ", with: "") ?? "") else {
            return false
        }
        return num1 < num2
    }
    // 3. 转换成「数字.Desc」的格式
    .map {
        guard let stepNum = $0["Step"]?.replacingOccurrences(of: "S ", with: ""),
              let desc = $0["Desc"] else {
            return ""
        }
        return "\(stepNum).\(desc)"
    }
    // 4. 用空格拼接成最终字符串
    .joined(separator: " ")

print(result)
// 输出:1.Do first step 2.Do second step 3.Do third step

步骤拆解:

  • 过滤:用filter筛选出Step字段以"S "开头的元素,直接排除掉P 1这类不需要的项。
  • 排序:把每个元素的Step字段去掉前缀"S ",转成整数后按升序排列,确保步骤1、2、3的顺序正确。
  • 格式化:用map把每个元素转换成指定的「数字.描述」格式字符串。
  • 拼接:最后用joined(separator: " ")把所有格式化后的字符串用空格连接起来,得到你要的最终格式。

如果需要把结果作为标签文本直接使用,result变量就是现成的字符串,直接赋值给标签的text属性即可~

内容的提问来源于stack exchange,提问作者Alejandro Vargas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 10:01:37