I am trying to dynamically create sections for List
with a header in SwiftUI.
here is my array:
var lists = [a list of names with A to Z] // array of strings
then I try to get first letter:
var firstCharacters: [Character] {
var firstCharacters = [Character]()
for list in lists.sorted(by: {$0 < $1}) {
if let character = list.first, !firstCharacters.contains(character) {
firstCharacters.append(character)
}
}
return firstCharacters
}
I created the list
like this:
List {
ForEach(firstCharacters, id: .self) { charachter in
Section(header: Text("(charachter.description)")) {
ForEach(Array(lists.enumerated()), id:.element) { index, element in
Text("Name (element), Id: (index)")
})
}
}
}
}
Now I have a problem adding section to the list now sure how can I combine with the list.
3
Answers
The following would print the names in each section:
Although a better way might be to not have 2 different arrays but merge them into one where the first letter is the key and the values are the names.
That way you don’t have to iterate over every name for every section.
A better way to section this is to take your list of words and turn it into a dictionary keyed by the first letter like this:
Then use the
Dict
in yourList
like this:This prevents you from having to iterate through the whole list for every letter. It is done once when creating the
Dict
. You no longer needvar firstChar
.My recommendation is a view model which groups an array of strings into a
Section
struct withDictionary(grouping:by:)
Whenever the content of the array is being modified the section array (and the view) is updated.
In the view in
onAppear
pass some names