SwiftUI: Multiplatform app swiftui unexpected platform condition

363 views Asked by At

I'm trying to implement a list in a Multiplatform implementation here is my implementation:

struct ContentView: View {
    var body: some View {
        List {
            Section(header: Text("Header"), footer: Text("Footer")){
                ForEach(0..<5){
                    Text("\($0)")
                        .tag($0)
                }
            }
            #if os(iOS)
                .listStyle(GroupedListStyle())
            #endif
        }
    }
}

But on this line:

.listStyle(GroupedListStyle())

I'm getting this error:

Unexpected platform condition (expected `os`, `arch`, or `swift`)

Any of you knows a way around this error?

I'll really appreciate your help

1

There are 1 answers

2
David Reich On BEST ANSWER

SwiftUI doesn't like conditional compilation code very much.

Try something like this:

#if os(macOS)
typealias MyListStyle = PlainListStyle
#else
typealias MyListStyle = GroupedListStyle
#endif
...
SomeView {}
.listStyle(MyListStyle())

Or

func myListStyle() -> some View {
    #if os(macOS)
    return listStyle(PlainListStyle())
    #else
    return listStyle(GroupedListStyle())
    #endif
}
...
SomeView {}
.myListStyle()

You can also use a variation of the func with a returned self for modifiers that aren't appropriate. I also used it to make .environment conditional.