SwiftUI Setup

SwiftUI Setup and App Structure

Before you start building beautiful interfaces, you need to understand how a SwiftUI application is structured.

Unlike older iOS apps that relied on storyboards and massive App Delegates, a pure SwiftUI app is incredibly lightweight.

Let's explore the core components that make up the starting point of every modern Apple app.


Requirements

To build SwiftUI apps, you absolutely need a Mac running macOS.

You must also download and install Xcode from the Mac App Store.

Xcode is Apple's official Integrated Development Environment (IDE) that includes the compiler, the visual editor, and the device simulators.

Make sure you are using a recent version of Xcode (Xcode 15 or newer is highly recommended) to get the latest SwiftUI features.


Creating Your First Project

Open Xcode and click "Create a new Xcode project".

Select "App" under the iOS tab.

When prompted for the Interface, ensure SwiftUI is selected (not Storyboard).

For the Language, ensure Swift is selected.


The App Protocol

When you generate a new project, Xcode creates an entry point file, usually named YourAppNameApp.swift.

This file contains a struct that conforms to the App protocol.

The App protocol represents the actual application itself and manages its lifecycle.

The App Entry Point:

import SwiftUI

// The @main attribute tells Swift this is the start of the app @main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } } }


Scenes and WindowGroups

Inside your App struct, you must provide a body that returns a Scene.

A Scene represents a window (or a group of windows) that displays your user interface.

The most common scene type is a WindowGroup.

On iOS, a WindowGroup usually represents the single full-screen window of your app. On macOS or iPadOS, it allows the user to open multiple windows of your app simultaneously!

Inside the WindowGroup, you place your starting View, which is typically ContentView().


The ContentView

The ContentView.swift file is where you will write your actual UI code.

This is the default view that appears on the screen when your app finishes launching.

From the ContentView, you can start adding text, buttons, images, and navigating to other screens.

Because SwiftUI is highly modular, you will eventually break your ContentView down into dozens of smaller, reusable custom views.


Exercise

Which attribute is used to designate the starting entry point of a SwiftUI application?