Home > Enterprise >  Is there an elegant way to handle the first and last element in a list specially in SwiftUI?
Is there an elegant way to handle the first and last element in a list specially in SwiftUI?

Time:07-28

So let's say I am rendering a list like so:


struct MyModel: Identifiable { ... }

let models = [MyModel]

var body: some View {
    VStack {
        ForEach(models) { model in 
            ...
        }
    }
}

Let's say for the first and last item in the list, I want to render in a different way. For instance, let's say I want to use a larger font size for the first item, and I want to draw a separator below all but the last item.

Is there an elegant/idiomatic way to handle the first and/or last item differently in a ForEach block in SwiftUI?

CodePudding user response:

If your MyModel conforms to Equatable, you can do this:

struct MyModel: Identifiable { ... }

let models = [MyModel]

var body: some View {
    VStack {
        ForEach(models) { model in
            if models.first == model {
                ...
            }

            if models.last == model {
                ...
            }

            ...
        }
    }
}
  • Related