rensbreur / SwiftTUI

SwiftUI for terminal applications
MIT License
1.23k stars 47 forks source link

Conditional views with empty else clause crashes #10

Closed hassila closed 1 year ago

hassila commented 1 year ago

Constructs like this crashes with a nil dereference:

        if let statistics {
                VStack {
                    HStack {
                        VStack {
                            Text("Table statistics")
                            TableStatisticsView(statistics: statistics)
                                .border()
                        }
                        Spacer()
                    }
                }
            } 

adding an else clause returning a different view get's it working:

else {
                Spacer()
            }

Seems conditional views can't handle the case of 'empty' - maybe 'EmptyView' could be exposed if an else clause is required? (I don't want to use a Spacer) - need scope change:

'EmptyView' initializer is inaccessible due to 'internal' protection level

Should this work, or must a view always be returned in else? If so, could we consider exposing EmptyView ?

rensbreur commented 1 year ago

Thanks for reporting 👍 I can reproduce a crash by wrapping a VStack in a conditional if. This should work without an EmptyView of course.

EmptyView should have a public initializer. If it works with an EmptyView, that could be a temporary work-around.

rensbreur commented 1 year ago

I found the issue. In checking whether a view node corresponds to a stack view, Swift will happily cast optional stacks (Optional<VStack<...>>) to stacks (VStack<...>), thus asking the nodes above the stack to do things that only stacks can do. I will add a fix later to make sure SwiftTUI nodes check if they belong to a non-optional stack. I will add a fix later.

This should affect stacks directly wrapped in if-statements without an else-clause, else-clauses with EmptyView aren't affected because they don't use Swift's Optional type. It may also affect modified views directly wrapped in if-statements.

hassila commented 1 year ago

Cool, thanks!

rensbreur commented 1 year ago

I've pushed a fix to master

hassila commented 1 year ago

Tested, verified - works fine, thank you!