Sort list alphabetically

Hi, I have an array of Strings and want to sort it with Sections from a to z in a list. How can I do it?
Answered by OOPer in 653584022
@Konste4sfi

want to sort it with Sections from a to z in a list

You need to create a structure which represents sections, and rows in each section.

A simplified example:
Code Block
import SwiftUI
struct ContentView: View {
var inputArray: [String] = [
"Andrew",
"Adam",
"David"
]
@State var groupedArray: [String: [String]] = [:]
var body: some View {
List {
ForEach(groupedArray.keys.sorted(), id: \.self) {key in
Section(header: Text(key)) {
ForEach(groupedArray[key]!, id: \.self) {value in
Text(value)
}
}
}
}
.onAppear {
groupedArray = Dictionary(
grouping: inputArray,
by: {$0.first?.uppercased() ?? ""}
).mapValues{$0.sorted()}
}
}
}


You may need to modify many parts of this code, depending on the details of your requirement.
What is the problem ?

Sorting the array ?

If the array is myArray, it is simply
Code Block
let sorted = myArray.sorted()

Just take care of upper/lower case. You could map the array first to make all strings start with uppercase.

And use it in List.
This may help
https://stackoverflow.com/questions/62189695/group-list-data-in-swiftui-for-display-in-sections
Hi I have the array sorted but I want it like the Contacts app on the iPhone, so that all Strings, whose first letter is "a", are in the Section "A" and so on. Do you understand what I mean?
Accepted Answer
@Konste4sfi

want to sort it with Sections from a to z in a list

You need to create a structure which represents sections, and rows in each section.

A simplified example:
Code Block
import SwiftUI
struct ContentView: View {
var inputArray: [String] = [
"Andrew",
"Adam",
"David"
]
@State var groupedArray: [String: [String]] = [:]
var body: some View {
List {
ForEach(groupedArray.keys.sorted(), id: \.self) {key in
Section(header: Text(key)) {
ForEach(groupedArray[key]!, id: \.self) {value in
Text(value)
}
}
}
}
.onAppear {
groupedArray = Dictionary(
grouping: inputArray,
by: {$0.first?.uppercased() ?? ""}
).mapValues{$0.sorted()}
}
}
}


You may need to modify many parts of this code, depending on the details of your requirement.
Sort list alphabetically
 
 
Q