Putting Dividers between Views, but ommiting EmptyView and without Divider at end

Viewed 48

In my situation, i want to create

Section
- Divider
Section
- Divider
Section
- Divider
Section

the Section is created by a separate View, but can return an actual view or an EmptyView, in that case it is ommited and no Divider is placed

moreover a Divider is never last

this looks very easy, but is quite tricky

struct SearchSectionView<T: DatabaseItem>: View {
    
    // ...
    
    var body: some View {
        if results.count == 0 {
            EmptyView()
        } else {
            //... create Views
        }
    }
    
}

// in parent
VStack {
    SearchSectionView<Class1>(...)
    SearchSectionView<Class2>(...)
    SearchSectionView<Class3>(...)
    SearchSectionView<Class4>(...)
}

NOTE 1:

If not in SwiftUI i would do as follows, which obviously doesn't work

let allViews = [
    SearchSectionView<Class1>(...)
    SearchSectionView<Class2>(...)
    SearchSectionView<Class3>(...)
    SearchSectionView<Class4>(...)
]
ForEach(Array(allViews.filter({ $0 != EmptyView() }).joined(separator: Divider()))) { view in
    view
}

NOTE 2:

Yes, i could add the Divider in the SearchSectionView but that becomes tricky too, as the isolated section doesn't know if the section after exists (eg not EmptyView)

0 Answers
Related