TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Sorting Nested Array in SwiftData

Forums > SwiftUI

Hey all, I'm having trouble figuring out how to sort a nested array within SwiftData.

here is how i have my model's designed:

@model
 class project {
   var columns: [Column] = []
}

@model
 class Column {
   var tasks: [Task] = []

    func sortTasks() {
       self.tasks.sort {$0.name < $1.name}
     }
 }

@model
class Task {
 var name: String
 var creationDate: Date = .now
}

I'm doing an @Query and forEach in ContentView but afterwards

@Query(sort: \Board.creationDate) var boards: [Board]

 ForEach(boards) { board in
        NavigationLink(value: board) {
               SideBarItemView(icon: board.icon, name: board.name)
                .tag(board)
         }
  }
  .navigationDestination(for: Board.self) { board in
        BoardView(board: board, columnVisibility: $columnVisibility)
  }

My BoardView code:

 @Bindable var board: Board

   ForEach(board.columns.sorted(by: {$0.creationDate < $1.creationDate})) { column in
        ColumnView(board: board, column: column)

     }

       Button(action: {
                column.sortTasks()
         }) {
              Label("Alphabetical", systemImage: "abc")
          }

Any help would be greatly appreciated.

   

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.