mercredi 28 avril 2021

Automatically populate view with heterogeneous values from a model

Let's pretend I have a model like the following:

struct Coupon: Identifiable {
    let id: Int
    let code: String
    let totalAmount: Double
    let spentAmount: Double
    let rate: Double
    let validFrom: Date
    let validTo: Date
    let supplier: Supplier
}

My intent is to build a SwiftUI card-like view displaying all the formatted information using a helper function like the following:

private func entry(for label: LocalizedStringKey, value: LocalizedStringKey) -> some View {
    HStack { Text(label); Spacer(); Text(value) }
}

I know I can use reflection to loop through the properties, and start doing some type checking to format dates, for example, but for doubles things are more complicated because some represent amounts but others don't. Another problem would be how to render the label for each property. Is there some even complex way to achieve this idea?





Aucun commentaire:

Enregistrer un commentaire