Swift convert an array to array of tuples

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:


tuples(key , value)


key


first character


value


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




1 Answer
1



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


prefix


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






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.

– Shivam Pokhriyal
Sep 15 '18 at 16:12






I updated the answer providing a more suitable solution.

– vadian
Sep 15 '18 at 16:21






Thanks for the solution!!

– Shivam Pokhriyal
Sep 15 '18 at 16:32






let sections = dictionary.map(Section.init)

– Leo Dabus
Sep 15 '18 at 19:59


let sections = dictionary.map(Section.init)



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

How do I collapse sections of code in Visual Studio Code for Windows?

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ