Home > OS >  How to sort a list with structs by date in SwiftUI?
How to sort a list with structs by date in SwiftUI?

Time:11-16

I have a struct like this:

import Foundation

struct Product: Identifiable {
    var name: String
    let expirationDate: Date
    let id = UUID()
}

and a list like this:

import SwiftUI

struct ContentView: View {
    
    @Binding var products: [Product]
    
    var dateFormatter: DateFormatter {
           let formatter = DateFormatter()
           formatter.dateStyle = .medium
           return formatter
       }
    
    var body: some View {
        
        VStack {
           List {
              ForEach(products) { product in
                 HStack {
                    Text(product.name)
                    Spacer()
                    Text(self.dateFormatter.string(from: product.expirationDate))
                 }
              }
           }
        }

how can I sort this list so that the closest expiration date from now is on top of the list?

I don't even know how to get just the expirationDates from products array. I would appreciate any help. Thank you in advance!

CodePudding user response:

You need to sort your array based on timeIntervalSinceNow:

$0.expirationDate.timeIntervalSinceNow < $1.expirationDate.timeIntervalSinceNow

Edit(Thanks to Martin R) You can compare Date directly:

$0.expirationDate < $1.expirationDate

So in your view, ForEach(products) becomes:

Foreach(products.sorted(by: {$0.expirationDate < $1.expirationDate}))
  • Related