Swift将数组转换为元组数组

时间:2018-09-15 15:19:03

标签: swift

我有一个像这样的数组:

[Shivam, Shiv, Shantanu, Mayank, Neeraj]

我只想根据tuples(key , value)keyfirst charactervalue的情况从此数组创建array of strings的数组:

赞:

[

(**key**: S , **value**: [Shivam, Shiv, Shantanu]),

 (**key**: M , **value**: [Mayank]), 

 (**key**: N , **value**: [Neeraj])

]

PS:这不是此帖子Swift array to array of tuples的重复项。 OP希望合并两个数组以创建元组数组

1 个答案:

答案 0 :(得分:3)

  • 第1步:创建分组字典

    let array = ["Shivam", "Shiv", "Shantanu", "Mayank", "Neeraj"]
    let dictionary = Dictionary(grouping: array, by: {String($0.prefix(1))})
    
  • 第2步:实际上,没有第2步,因为不鼓励您使用元组进行持久数据存储,但是如果您确实想要元组数组,则不予考虑

    let tupleArray = dictionary.map { ($0.0, $0.1) }
    

比元组更好的数据模型是例如自定义结构

struct Section {
    let prefix : String
    let items : [String]
}

然后将字典映射到该结构,并按prefix

对数组进行排序
let sections = dictionary.map { Section(prefix: $0.0, items: $0.1) }.sorted{$0.prefix < $1.prefix}
print(sections)