使用逗号分隔符从字典数组中的字典中添加每100个字符串键

时间:2017-09-04 00:46:18

标签: swift string dictionary key

所以我有一个包含450或有时1313个字符串键的字典,我想在字符串数组中添加所有键,因此earch字符串必须包含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"]

1 个答案:

答案 0 :(得分:2)

您只需使用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"]