Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

swift - Add every 100 string keys from dictionary in array of strings with comma separator

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"]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...