Let list =["Car", "Bike", "Plane", "Boat"]
for(index, element) inlist.enumerated() {
print(index, ":", element)
}
//
print:
0 : Car
1 : Bike
2 : Plane
3 : Boat
List with Sections
VStack {
List {
ForEach(countries, id: \.self) { country in
Section(country.wrappedFullName) {
ForEach(country.candyArray, id: \.self) { candy in
Text(candy.wrappedName)
}
}
}
}
Sorted List
// FIRST METHOD
struct User: Identifiable {
let id = UUID()
let firstName: String
let lastName: String
}
struct ContentView: View {
let users = [
User(firstName: "Arnold", lastName: "Rimmer"),
User(firstName: "Kristine", lastName: "Kochanski"),
User(firstName: "David", lastName: "Lister"),
].sorted {
$0.lastName < $1.lastName
}
//.............................
// SECOND METHOD
struct User: Identifiable {
let id = UUID()
let firstName: String
let lastName: String
static func <(lhs: User, rhs: User) -> Bool {
lhs.lastName < rhs.lastName
}
}
struct ContentView: View {
let users = [
User(firstName: "Arnold", lastName: "Rimmer"),
User(firstName: "Kristine", lastName: "Kochanski"),
User(firstName: "David", lastName: "Lister"),
].sorted()
}
The result is the same on both methods. The benefit is, in case of using this list everywhere with same sorting method, we can change the sorting method in the struct and it changes everywhere we use the list.