Menu
Coddy logo textTech

Conditional Views

Part of the Introduction to SwiftUI section of Coddy's Swift journey. Lesson 22 of 50.

An if inside a body decides whether a view is there at all:

@State private var showDetails = false

var body: some View {
    VStack {
        Button("Show details") {
            showDetails.toggle()
        }
        if showDetails {
            Text("Made with SwiftUI")
        }
    }
}

While showDetails is false the text is not part of the screen. After the tap it appears. An else branch shows a different view instead:

if isLoggedIn {
    Text("Welcome back")
} else {
    Button("Log in") { isLoggedIn = true }
}
challenge icon

Challenge

Easy

The text Made with SwiftUI should only appear after the user taps Show details. Make the button set showDetails, and show the text (with its identifier) only when showDetails is true.

Try it yourself

import SwiftUI

@main
struct CoddyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction to SwiftUI

Practice on your own: Swift playground