How to sort(by: ) list the correct way in SwiftUI?

Viewed 744

I am trying to sort my list the way I have in my modal to show it on my view but for reason when I use sort(by: >) it just shows the first element and the rest of the list is randomly generate. How can I make this work by sorting it the way I have in my modal like this: Pillars, Events, More, and Gallery. If you need more info check this link.

here is my code:

VStack {
    ForEach(categories.keys.sorted(by: >), id: \.self) { key in
        CategoryRow(categoryName: key, items: self.categories[key]!)
    }
}

Modal:

enum Category: String, CaseIterable, Codable, Hashable {
    case pillars, events, more, gallery
      
    var displayName: String {
        switch self {          
        case .pillars: return "Pillars"        
        case .events: return "Events" 
        case .more: return "More"    
        case .gallery: return "Gallery"
        }
    }
}
1 Answers

Here is the way to use the sorted(by:) function.

    List(categories.sorted(by: alphabetical)) { c in
        CategoryRow(category: c)
    }
    func alphabetical(lhs: Category, rhs: Category) -> Bool {
        return lhs.name < rhs.name
    }

More concise :

List(categories.sorted { $0.name < $1.name } ) { c in
        CategoryRow(category: c)
    }
Related