Shivam Pokhriyal
Shivam Pokhriyal

Reputation: 489

Swift convert an array to array of tuples

I have an array like this:

[Shivam, Shiv, Shantanu, Mayank, Neeraj]

I want to create an array of tuples(key , value) from this array only with key being first character and value being an array of strings:

Like this:

[

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

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

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

]

PS: It is not a duplicate to this post Swift array to array of tuples. There OP wants to merge two arrays to create an array of tuples

Upvotes: 1

Views: 1006

Answers (1)

vadian
vadian

Reputation: 285082

  • Step 1: Create a grouped dictionary

    let array = ["Shivam", "Shiv", "Shantanu", "Mayank", "Neeraj"]
    let dictionary = Dictionary(grouping: array, by: {String($0.prefix(1))})
    
  • Step 2: Actually there is no step 2 because you are discouraged from using tuples for persistent data storage, but if you really want a tuple array

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

A better data model than a tuple is a custom struct for example

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

then map the dictionary to the struct and sort the array by prefix

let sections = dictionary.map { Section(prefix: $0.0, items: $0.1) }.sorted{$0.prefix < $1.prefix}
print(sections)

Upvotes: 5

Related Questions