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)
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
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