NEW: Learn SwiftUI with my free YouTube video series! >>

< How to layer views on top of each other using ZStack   How to create views in a loop using ForEach >

How to return different view types

When we return some View from the body of our views, Swift understands that to mean we have one specific return type. For example, if we wanted to flip a coin and show either a “you won!” image or some text that says “Better luck next time”, we can’t write this:

var body: some View {
    if Bool.random() {
        Image("example-image")
    } else {
        Text("Better luck next time")
    }
}

That might return either an image or a text view, which isn’t allowed – we must return precisely one type.

There are two ways you can fix this. The first option is to wrap your output in a group, so that no matter whether you send back an image or a text view they both go back in a group:

var body: some View {
    Group {
        if Bool.random() {
            Image("example-image")
        } else {
            Text("Better luck next time")
        }
    }
}

Alternatively, SwiftUI gives us a type-erased wrapper called AnyView that we can return:

var body: some View {
    if Bool.random() {
        return AnyView(Image("example-image"))
    } else {
        return AnyView(Text("Better luck next time"))
    }
}

If you haven’t heard of this concept, it effectively forces Swift to forget about what specific type is inside the AnyView, allowing them to look like they are the same thing. This has a performance cost, though, so don’t use it often.

Although both Group and AnyView achieve the same result for our layout, it’s generally preferable to use Group because it’s more efficient for SwiftUI.

LEARN SWIFTUI FOR FREE I wrote a massive, free SwiftUI tutorial collection, and also have a growing list of free SwiftUI tutorials on YouTube – get started today!

< How to layer views on top of each other using ZStack   How to create views in a loop using ForEach >
MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 5.0/5

Click here to visit the Hacking with Swift store >>