【问题标题】:Add every 100 string keys from dictionary in array of strings with comma separator使用逗号分隔符将字典中的每 100 个字符串键添加到字符串数组中
【发布时间】:2017-09-04 00:46:17
【问题描述】:

所以我有一个包含 450 个或有时 1313 个字符串键的字典,我想将所有键添加到字符串数组中,因此每个字符串必须包含 1 到 100 个键,这取决于字典的大小。 例如,如果有 450 个键:

let array = ["first 100 keys here comma separated","second 100 keys here comma separated","third 100 keys here comma separated","fourth 100 keys here comma separated","and last 50 keys comma separated"]

【问题讨论】:

  • 你已经有代码了吗?
  • 不,我只有字典里的键。

标签: swift string dictionary key


【解决方案1】:

您只需对数组元素进行分组并使用 map 使用 joined(separator: ", ") 加入您的键:

extension Array {
    func group(of n: IndexDistance) -> Array<Array> {
        return stride(from: 0, to: count, by: n)
        .map { Array(self[$0..<Swift.min($0+n, count)]) }
    }
}

测试:

let dic = ["f":1,"a":1,"b":1,"c":1,"d":1,"e":1, "g": 1]
let arr = Array(dic.keys).group(of: 2).map{
    $0.joined(separator: ", ")
}
arr  //["b, a", "c, f", "e, g", "d"]

【讨论】:

  • 在哪里可以学习这些功能组和地图,并在操场上玩?你是从哪里学习 Swift 的?
  • @BogdanBogdanov 我用 Swift 编码已经 3 年多了,所以你会自然而然地学习到这一点。 SO 有很多关于如何使用它们的示例。
  • 是的,我也是从 Swift 开始编程的,但我不像你那样对语言有那么深的了解。我在 App Store 中已有 5 个获批的应用
  • @LeoDabus 如果将此扩展推广到RandomAccessCollection,则无需将dic.keys 提升为Array
猜你喜欢
  • 2022-01-13
  • 1970-01-01
  • 2017-04-10
  • 2017-12-24
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多