1

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

0

1 Answer 1

5
  • 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)
Sign up to request clarification or add additional context in comments.

4 Comments

Actually I first used Dictionary only, but later on i had to sort the dictionary based on the key that is characters but couldn't do it. Tried everything to sort dictionary but couldn't so i moved on to array of tuples. I will try your answer and let you know.
I updated the answer providing a more suitable solution.
Thanks for the solution!!
let sections = dictionary.map(Section.init)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.