top of page
Writer's pictureHui Wang

39. SwiftUI: Introducing Group and AnyView

Today I will show you how to use Group and AnyView.


Steps:

  • First, add a random Bool that is used to determine which view to display.

private var randomBool = Bool.random()

  • The body needs to return a view as the only property of the View protocol.

  • The keyword "return" is by default, so adding a "return" is the same meaning.

var body: some View {
    return Text("Hello World!")
}

  • Determine whether to return Text based on the value of the Bool property

  • If the property's value is true, return the first Text.

  • Otherwise, return the second Text.

if randomBool {
    return Text("Hello, I am the first Text!")
} else {
    return Text("Sorry, I am the second Text!")
}

If we want to remove the "return" keyword, we can use "Group."

Since "Group" combines the internal subviews into a single view, Xcode will automatically infer its return type.

var body: some View {
    Group {
        if randomBool {
            Text("Hello, I am the first Text!")
        } else {
            Text("Sorry, I am the second Text!")
        }
    }
}

  • To introduce AnyView, we replace the second Text with an Image.

if randomBool {
    Text("Hello, I am the first Text!")
} else {
    Image(systemName: "questionmark.circle.fill")
        .font(.system(size: 100))
}

  • Set the body property to type AnyView so it can accept any return.

  • Delete "Group."

  • Returns a Text when the boolean value is true. Because we are using AnyView, the Text will be force converted to the AnyView type.

  • Returns an Image when the boolean value is false. Image will also be force converted to the AnyView.

var body: AnyView {
    if randomBool {
        return AnyView(Text("Hello, I am the first Text!"))
    } else {
        return AnyView(Image(systemName: "questionmark.circle.fill")
            .font(.system(size: 100)))
    }
}

AnyView and Group have similar effects, but Group is recommended because it performs more efficiently.


  • Finally, use "Editor"->"Canvas"->"Refresh Canvas" to refresh the screen to see the results.


Source Code:

  • Group

struct ContentView: View {
    private var randomBool = Bool.random()
    
    var body: some View {
        Group {
            if randomBool {
                Text("Hello, I am the first Text!")
            } else {
                Image(systemName: "questionmark.circle.fill")
                    .font(.system(size: 100))
            }
        }
    }
}

  • AnyView

struct ContentView: View {
    private var randomBool = Bool.random()
    
    var body: AnyView {
        if randomBool {
            return AnyView(Text("Hello, I am the first Text!"))
        } else {
            return AnyView(Image(systemName: "questionmark.circle.fill")
                .font(.system(size: 100)))
        }
    }
}

 

Follow me on:

Comments


bottom of page