SwiftUI App Structure

App Struct: Your App’s Heart

The App struct is the central building block that defines the overall composition and behavior of your SwiftUI application. Every SwiftUI app must have one, and only one, main App struct. This is where you outline the top-level views of your app, how they’re connected, and the navigation flow.

In SwiftUI, the main App struct conforms to the App protocol. This protocol has a key requirement: You must implement a body property that returns a Scene.

Key Components

  1. The @main Attribute:
  • This attribute designates a specific struct as the entry point to your application’s code. When your app launches, the struct marked with @main kicks off the execution.
  1. The App Struct:
  • Conforms to the App protocol.
  • Implements the computed property body, which returns a Scene.
  1. Scenes:
  • Scene is an important protocol in SwiftUI. Scenes represent the primary units of content that your application displays.
  • Common scene types: WindowGroup: Represents a window in your application. DocumentGroup: Represents a document-based interface. Settings: Represents an interface for viewing and modifying a macOS app’s settings.
import SwiftUI

@main
struct MyApp: App {
  var body: some Scene {
    WindowGroup {
      ContentView()
    }
  }
}

Views: Your UI’s Building Blocks

  • Fundamental Units: Views in SwiftUI are the core elements that define what the user sees and interacts with. Every text element, button, image, and custom component you create is a view.

  • The View Protocol: To be recognized as a legitimate view in SwiftUI, a struct must conform to the View protocol. This protocol has one primary requirement: to implement a computed property called body that returns some View.

  • Composability: The true power of views lies in their ability to be nested and combined to form complex layouts. A parent view can contain multiple child views, creating a hierarchical struct.

  • Declarative Syntax: SwiftUI’s declarative nature means you describe the desired appearance and layout of your views, and the framework handles rendering them efficiently.

struct ContentView: View {
  var body: some View {
    VStack { // A vertical container view
      Text("Welcome to My App")
    }
  }
}

How SwiftUI Components Work Together

  1. App Struct

    • The App struct serves as the stage upon which your application unfolds.
    • It defines the primary scenes of your application, establishing the overall navigational framework for the user.
  2. Views

    • Views are the actors playing different roles on this stage.
    • They represent the text, images, buttons, and all other visual elements the user interacts with.
    • The app struct dictates a hierarchy of views, defining how they relate and are arranged.
See forum comments
Download course materials from Github
Previous: Introduction Next: SwiftUI App Walk Through