Skip to main content
Swift for iOS Development
CHAPTER 10 Beginner

Introduction to SwiftUI

Updated: May 16, 2026
7 min read

# CHAPTER 10

Introduction to SwiftUI

1. Introduction

For the past 9 chapters, we have been running raw Swift logic in the console. We know how to calculate data, but an iPhone app is visual. It has buttons, scrolling lists, and animations. To draw these elements, we use a UI Framework. In 2019, Apple revolutionized the industry by releasing SwiftUI. In this chapter, we transition from pure logic to visual engineering. We will master the Introduction to SwiftUI, exploring its declarative nature, understanding the mandatory View protocol, and leveraging the immense power of the Xcode Live Canvas.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Explain the difference between Declarative UI (SwiftUI) and Imperative UI (UIKit).
  • Understand the @main App lifecycle entry point.
  • Implement the fundamental View protocol and its body requirement.
  • Stack multiple View Modifiers to style UI elements.
  • Utilize the Xcode Canvas to preview UI changes instantly.

3. Declarative vs Imperative UI

In the old days of UIKit (Imperative), building a screen was like giving a robot step-by-step instructions:
  1. 1. "Create a button."
  1. 2. "Move it 50 pixels down."
  1. 3. "Color it blue."
  1. 4. "Add it to the screen."

In SwiftUI (Declarative), you don't give instructions. You simply declare *what* you want the final result to be, and the engine figures out how to draw it! *"I want a blue button with 50 pixels of padding."* That's it!

4. The App Lifecycle (@main)

When a user taps your app icon on their iPhone, where does the code actually start? Every SwiftUI app has a single file marked with @main. This is the absolute root of your application.
swift
1234567891011
import SwiftUI

@main
struct MyAwesomeApp: App {
    var body: some Scene {
        WindowGroup {
            // This tells the app which Screen to load first!
            ContentView() 
        }
    }
}

5. The View Protocol

In SwiftUI, *everything* is a View. A button is a View. A screen is a View. Even empty space is a View. To create a custom screen, you create a Swift struct and tell it to conform to the View protocol. The *only* strict rule of the View protocol is that your struct MUST contain a computed property named body that returns some View.
swift
123456789101112
import SwiftUI

// 1. We create a Struct conforming to the View protocol
struct ContentView: View {
    
    // 2. We MUST provide the 'body' property
    var body: some View {
        
        // 3. We declare what we want to see!
        Text("Welcome to SwiftUI!")
    }
}

6. The Magic of Modifiers

A raw Text component is boring. We use Modifiers to change its appearance. Modifiers are just functions that you attach to a View using a dot .. *Crucial Rule: Modifiers return a brand new View! This means you can chain them together infinitely.*
swift
1234567891011
struct ContentView: View {
    var body: some View {
        Text("Welcome to SwiftUI!")
            .font(.largeTitle)          // Makes it huge
            .fontWeight(.heavy)         // Makes it thick
            .foregroundColor(.white)    // Text color
            .padding(20)                // Adds breathing room inside the box
            .background(Color.blue)     // Background box color
            .cornerRadius(10)           // Rounds the corners of the background box!
    }
}

*(Notice the order matters! If you put .background BEFORE .padding, the blue background will only cover the text tightly, and the padding will be added outside the blue box!)*

7. The Xcode Canvas (Live Preview)

You do not need to hit "Play" and wait for the Simulator to load just to see if your text is blue. At the bottom of every SwiftUI file, Xcode generates a PreviewProvider. This tells the Canvas (the right-hand panel in Xcode) to render a live, interactive visualization of your code as you type!
swift
123
#Preview {
    ContentView() // Instantly renders the screen on the right side of your Mac!
}

8. Mini Project: Welcome App UI

Let's build a clean, modern Welcome pill.
swift
12345678910111213141516171819202122
import SwiftUI

struct WelcomeView: View {
    var body: some View {
        Text("iOS Developer")
            .font(.title2)
            .bold()
            .foregroundColor(.white)
            .padding(.horizontal, 40) // 40px padding on Left/Right
            .padding(.vertical, 15)   // 15px padding on Top/Bottom
            .background(
                // We can use Gradients as backgrounds!
                LinearGradient(colors: [.purple, .blue], startPoint: .leading, endPoint: .trailing)
            )
            .clipShape(Capsule()) // Perfectly rounds the edges into a pill shape
            .shadow(radius: 10)   // Adds a drop shadow!
    }
}

#Preview {
    WelcomeView()
}

9. Common Mistakes

  • Returning Multiple Views: The body property is strictly configured to return exactly ONE view. If you try to write two Text components on top of each other:
``swift var body: some View { Text("Hello") Text("World") // CRASH! The compiler doesn't know how to arrange them. } ` *(We will learn how to fix this using Stacks in the very next chapter!)*

10. Best Practices

  • Extracting Views: If your body property gets longer than 50 lines because you have 20 modifiers, your code is unreadable. Highlight a block of UI code in Xcode, Right-Click, and select "Extract Subview". Xcode will automatically move it into a smaller, reusable struct!

11. Exercises

  1. 1. Create a ContentView struct that outputs a Text component saying "My First App".
  1. 2. Add modifiers to make the text green, give it a black background, and add padding.

12. Coding Challenges

Challenge: Replicate the Mini Project from Section 8, but change the
LinearGradient colors to transition from .red to .orange, and change the .clipShape from Capsule() to Circle(). Observe what happens to the shape in the Live Preview!

13. MCQ Quiz with Answers

Question 1

What is the fundamental difference between SwiftUI's declarative paradigm and legacy imperative UI programming?

Question 2

When conforming a Swift struct to the View protocol, what specific computed property is absolutely mandatory for the compiler to accept it?

14. Interview Questions

  • Q: Explain the purpose of the @main attribute in a modern SwiftUI application lifecycle.
  • Q: Detail the concept of "View Modifiers" in SwiftUI. Why is the sequence in which modifiers (like .padding() and .background()) are applied architecturally critical to the final visual render?
  • Q: Why did Apple heavily lean into utilizing structs (Value Types) for SwiftUI Views rather than traditional classes (Reference Types)? How does this impact rendering performance?

15. FAQs

Q: Can I use SwiftUI if I have an old app written in UIKit? A: Yes! Apple provides wrapper components (
UIHostingController) that allow you to seamlessly inject brand new SwiftUI screens directly into the middle of a 10-year-old UIKit application!

16. Summary

In Chapter 10, we transitioned from backend logic to frontend aesthetics. We embraced Apple's revolutionary SwiftUI framework, leaving behind the tedious instructions of imperative code for elegant Declarative syntax. We identified the
@main application entry point and constructed visual structures conforming to the strict View` protocol. Finally, we mastered the art of chaining Modifiers to style components rapidly, leveraging the real-time feedback of the Xcode Canvas preview.

17. Next Chapter Recommendation

We know how to draw a beautiful, highly styled Text box. But what if we want an Image *above* the Text, and a Button *below* the Text? A single View is not enough. Proceed to Chapter 11: SwiftUI Views and Layouts.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·