Add every 100 string keys from dictionary in array

2019-09-21 21:00发布

问题:

So I have a dictionary with 450 or sometimes 1313 string keys and I want to add all keys in array of strings, so earch string has to contains from 1 to 100 keys it depends how big is the dictionary. Example if there are 450 keys:

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:

You just need to group your array elements and use map to join your keys using 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)]) }
    }
}

Testing:

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