Swift - Combine two Entities in one List and Sort them by date

Viewed 47

I have a project with three entities: A One to Many Relationship form TransactionEntity to PurchaseEntity and SellEntity. I want to list the transactions of the two Entities inside one list and sort them by date or type of transaction(Purchase or sell). As an example: 01.01.2022 Purchase 02.01.2022 Purchase 03.01.2022 Sell 04.01.2022 Purchase.

I tried something like:

Struct Detail: View {
@StateObject var transaction: Transaction

var body: some View {

VStack {
ForEach(transaction.purchaseArray, transaction.sellArray) { transaction in

VStack {
Text(„\(transaction.purchaseArray.name ?? „“)„)
Text(„\(transaction.purchaseArray.value ?? „“)“)
Text(„\(transaction.purchaseArray.date ?? „“)“)
}
VStack {
Text(„\(transaction.sellArray.name ?? „“)„)
Text(„\(transaction.sellArray.value ?? „“)“)
Text(„\(transaction.sellArray.date ?? „“)“)
}

}
}

}
}

But that doesn’t work. But how can I display two entities in one list and sort them?

enter image description here

1 Answers

Answer

You have to create a Protocol and let all of your Entities conform to it. Then you can define and Array and set its Type to the Protocol, which allows you to add all three Entities to it.


Code

protocol Entity: Hashable {
   var date: Date { get }
}

extension EntityA: Entity {
    var date: Date { a_purchDate }
}
extension EntityB: Entity {
    var date: Date { div_date }
}

struct Main: View {
    let entities: [any Entity]

    var body: some View {
        ForEach(sortedEntities, id: \.self) { entity in 
            Text(entity.date.stringify()) // Note, that the Method stringify is not part of Foundation.
        }
    }

    private var sortedEntities: [any Entity] {
        return entities.sorted { $0.date < $1.date }
    }
}
Related