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

Day 53 – Project 11, part one - Usage of Return

Forums > 100 Days of SwiftUI

Hey there,

Just going through Project 11, part 1 of Bookworm and i noticed in the code there's a return in ContentView. Was just wondering if there's any particular reason for this?

struct ContentView: View {
    @Environment(\.horizontalSizeClass) var sizeClass

    var body: some View {
        if sizeClass == .compact {
            return HStack {
                Text("Active size class:")
                Text("COMPACT")
            }
            .font(.largeTitle)
        } else {
            return HStack {
                Text("Active size class:")
                Text("REGULAR")
            }
            .font(.largeTitle)
        }
    }
}

It runs fine without the return keyword. Usually we don't need to use the return here. I hope to understand why return is used here.

2      

hi,

i think this is just a consequence of moving from the original SwiftUI (when BookWorm was created) to SwiftUI 2. i think initially the body property did not allow @ViewBuilder syntax, so once you put real executable code into the body (e.g., if or let statements), then you had to supply an explicit return of a View.

hope that helps (even more, i hope that's right!),

DMG

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.