Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 46 ยท Getting Started

Swift Features SwiftUI Relies On

The Swift features behind SwiftUI code: structs, closures and trailing closure syntax, opaque some View, property wrappers and result builders, with a runnable builder.

SwiftUI code looks like a new language, with views nested inside views and no return in sight. It is not. It is ordinary Swift, using a handful of language features in a very deliberate way. When you know those features, the syntax stops being magic, and the error messages start making sense.

This lesson is a tour of the five features you will see in almost every view: structs, closures, opaque types, property wrappers and result builders. Each one has its own lesson in the Swift track, which we link to rather than repeat. Here you see how SwiftUI uses them, and you build a tiny result builder yourself.

Five features behind the syntax

Structs Views are cheap value types.
Closures Button actions and content blocks.
some View An opaque return type.
@State and friends Property wrappers add behavior.

A fifth one ties them together, the result builder.

1 / 2

Structs and value semantics

Every view is a struct. Structs are value types: copying one gives an independent value, and there is no shared identity or inheritance. The memberwise initializer gives you a free init for stored properties, which is why this works without writing one:

Swift
struct RatingView: View {
    let stars: Int
    var body: some View {
        Text(String(repeating: "โ˜…", count: stars))
    }
}

RatingView(stars: 4)   // memberwise init

Because views are values, a parent creates a new child value each time its body runs, passing fresh data. Children never keep a hidden reference to a parent's variables. Data flows in through properties, which is the foundation of the state lessons that follow.

Closures and trailing closures

SwiftUI is full of closures: blocks of code passed as arguments. A Button takes one for its action and one for its label:

Swift
Button(action: { count += 1 }) {
    Text("Add")
}

When the last parameter is a closure, you may write it after the parentheses (a trailing closure), and drop the parentheses entirely if nothing else remains:

Swift
VStack(spacing: 8) {      // spacing in parentheses, content as trailing closure
    Text("One")
    Text("Two")
}

Button("Add") { count += 1 }   // title, then the action as a trailing closure

So a layout container is just a function call whose last argument happens to be a block that lists children. Once you see VStack { ... } as "call VStack, pass a closure", nested layouts read like plain Swift.

Opaque types: some View

The body property returns some View. In the Swift track, opaque types are explained in detail. For SwiftUI the practical meaning is this:

  • Every view modifier returns a new, wrapping type, so Text("Hi").bold().padding() has a long nested type name.
  • You would never want to write that name, and it changes when you add a modifier.
  • some View says "one specific view type, chosen by the implementation, which the compiler knows exactly".

That last part is what separates it from a protocol box (any View). With some View the compiler keeps the real type, so SwiftUI can compare and optimize trees efficiently. A consequence is that all branches of your body must produce the same type, and that is the reason if inside body needs help from a result builder, below.

Property wrappers

A property wrapper is a type that adds behavior to a stored property. You write @Something before the declaration. SwiftUI uses them to attach data-flow rules:

Swift
struct CounterView: View {
    @State private var count = 0          // storage owned by SwiftUI, survives body calls
    @Environment(\.dismiss) private var dismiss   // read a value from the environment
    @AppStorage("username") private var username = ""   // backed by UserDefaults

    var body: some View {
        Button("Count: \(count)") { count += 1 }
    }
}

A wrapper can also expose a projected value, written with a $ prefix. For @State, $count is a binding: a read-write reference to the state that child controls (such as a TextField) can use. The next chapter is devoted to this.

The stand-in below shows the mechanism in plain Swift: a wrapper that records every write, and a projected value that exposes the history. It is not @State, but it is the same language feature.

Swift Stand-in: a property wrapper with a projected value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Result builders: why a body has no return

How does a closure like this produce a single view when it contains three statements and no return?

Swift
VStack {
    Text("Title")
    Text("Subtitle")
    Image(systemName: "star")
}

The closure's parameter is marked with @ViewBuilder, a result builder (see result builders). A result builder rewrites a block of expressions into calls on a builder type. Conceptually, the three lines above become one combined value, something like TupleView(Text, Text, Image). The same machinery gives if, if/else and switch meaning inside views: each branch is converted to the same builder type, so both branches can differ in view type even though some View requires one type.

You can write a small builder yourself. This one collects strings, supports if, and joins them into lines, just like @ViewBuilder collects views.

Swift A tiny result builder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The closure body has no return and no array literal. The builder gathers each line, and if becomes buildOptional or buildEither. That is the entire trick behind SwiftUI's declarative look.

Reading SwiftUI code with this lens

Take one more look at a typical view and name each feature:

Swift
struct ProfileRow: View {                       // struct conforming to View
    let name: String                            // plain stored property
    @State private var isFollowing = false      // property wrapper

    var body: some View {                       // opaque return type
        HStack {                                // trailing closure + @ViewBuilder
            Text(name)
            Spacer()
            Button(isFollowing ? "Following" : "Follow") {   // trailing closure action
                isFollowing.toggle()
            }
        }
    }
}

When you meet an unfamiliar SwiftUI API, ask which of these features it uses: it is almost always one of them. If an error message is confusing (for example, "Type of expression is ambiguous"), the cause is often a closure the compiler cannot type-check; commenting out lines or extracting a subview helps you find it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In Button("Add") { count += 1 }, what is the { count += 1 } part?

    When the last parameter is a closure, it can follow the parentheses as a trailing closure. Here it is the button's action.
  2. 2. Why does a view's body return some View instead of a concrete type name?

    Opaque types hide one specific type. The compiler still knows it, which lets SwiftUI compare and optimize view trees.
  3. 3. What does the $ prefix on a property such as $count usually give you in SwiftUI?

    A property wrapper may expose a projectedValue, reached with $. For @State it is a Binding.
  4. 4. What makes if statements inside a VStack closure work without a return?

    Result builders rewrite a block of statements into calls on a builder type, including buildOptional and buildEither for conditions.

Summary

  • Views are structs: cheap value types with memberwise initializers.
  • Closures and trailing closure syntax make VStack { ... } and Button("x") { ... } ordinary function calls.
  • some View is an opaque return type: one hidden but exact type.
  • Property wrappers like @State add storage and behavior; $name is the projected value.
  • @ViewBuilder is a result builder that combines statements and conditionals into one view.

Next: Text, Images and SF Symbols