I have some trouble to extract the data from a list of objects, i am learning functional programming concepts.
struct Country {
let name: String
}
let country1 = Country(name: "Algeria")
let country2 = Country(name: "Angola")
let country3 = Country(name: "Belgium")
let countries = [country1, country2, country3]
What i want to do is a dictionary with the key the first character and the value is the list of all the countries witch begin with this character. In my example i will get:
let dic = ["A": [country1, country2], "B":[country3]]
I know how to do it with the "ugly" for loops. Like this:
for country in countries {
let first = country.name.first
if !sections.keys.contains(first) {
let matchedCountries = countries.filter {$0.name.hasPrefix(first)}
sections[first] = matchedCountries
}
}
My question is: Is there an easy way to do it with a more functional manner ?