Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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}))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading