UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Day 33 - Showing and hiding views with transitions. Question about Views in if-statements

Forums > 100 Days of SwiftUI

Shouldn't the following code be not allowed?

if isShowingRed {
    Rectangle()
        .fill(Color.red)
        .frame(width: 200, height: 200)
}

Here https://www.hackingwithswift.com/books/ios-swiftui/conditional-modifiers it's said "some View means one specific type of View will be returned, but we don’t want to say what". Since the if statement ensures that there are different returns depending on the value of isShowingRed this can't run, or can he?

2      

Since the if statement ensures that there are different returns depending on the value of isShowingRed this can't run, or can he?

There actually aren't different return types.

If you take some SwiftUI code like this:

    var body: some View {
        VStack {
            Rectangle()

            if showTwoRects {
                Rectangle()
            }
        }
    }

and check its type, you will find that it is:

VStack<TupleView<(Rectangle, Optional<Rectangle>)>>

So regardless of whether the second Rectangle is shown or not, the type is still the same because the conditional is incorporated into the type. The type is the same, even if what is actually displayed on screen is different.

2      

So whenever there are Views inside an if statement they are wrapped in an Optional<View>, aren't they?

2      

Yep, if it's a simple if. If it's an if else, the two branches go into a _ConditionalContent:

        VStack {
            Rectangle()

            if twoRects {
                Rectangle()
            } else {
                RoundedRectangle(cornerRadius: 8)
            }
        }
VStack<TupleView<(Rectangle, _ConditionalContent<Rectangle, RoundedRectangle>)>>

2      

Thank you, now it's all clear

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.