Swift and SwiftUI Foundations

1. Structures and Protocols

swift
struct ContentView: View {
    var body: some View {
        Text("Hello")
    }
}
  • struct declares a structure, a value type.
  • ContentView is the structure’s name.
  • : View declares conformance to the View protocol: ContentView behaves like a View.
  • A protocol is a description of behavior: a list of properties and functions without implementations that conforming types must provide.
  • Structs can contain properties, methods, and initializers.
  • Structs have no inheritance, but a struct can conform to many protocols.

Protocol conformance establishes a contract, not a parent–child class relationship.

The contract has two sides:

  • Obligation. To behave like a View, a type must implement var body: some View.
  • Reward. Once it does, it gains everything View offers, including hundreds of view modifiers such as .padding() and .foregroundStyle(_:), which are defined in protocol extensions on View.

2. Variables and the Type System

swift
var i: Int = 0
let number = 10
  • var declares a mutable variable; let declares an immutable constant.
  • : Int gives the type; = 0 gives an initial value.
  • Int and String are not built into the language. They are structs in the standard library.

: Int and : View read alike but mean different things. Int is a concrete type, so i is an Int. View is a protocol, so ContentView behaves like a View.

Static typing and type inference. Swift is statically typed: every variable has a type fixed at compile time. The type can often be inferred.

swift
let number = 10

number is inferred as Int.

Every value is initialized before use. A variable cannot be read before it has a value. A stored property of a struct gets its value in one of three ways:

swift
struct Greeting: View {
    var count: Int = 0
    var name: String

    var body: some View {
        Text("Hello, \(name)")
    }
}

Greeting(name: "Swift")
  1. A default value, like count.
  2. No default, like name. Then whoever creates the struct must supply it. Swift generates a memberwise initializer, so Greeting(name: "Swift") is the only way to make one.
  3. A custom initializer (init) that assigns it.

Optionals. Absence is a type, not a missing value.

swift
var number: Int? = nil

Int? is Optional<Int>: either a wrapped Int or nil.

3. Computed Properties and some View

swift
var body: some View {
    Text("Hello")
}

body is a computed property, not a stored one.

  • Its value is produced by running the code in braces, every time it is read.
  • It works like a function with no arguments that only returns a value.
  • SwiftUI decides when a view’s body needs to be evaluated again.

some View is an opaque type:

  • The value is one specific concrete type that conforms to View.
  • The compiler works out that concrete type from the code in body.
  • Callers know only that it is “some View”.

So everything in body must resolve to a single concrete type.

4. View Composition: the Lego Analogy

SwiftUI interfaces are assembled from smaller views, and every piece in the analogy is itself a View.

LegoSwiftUIExample
BrickBasic viewText, Circle
HelicopterCustom viewMyView
BagHolds viewsTupleView
ManualArranges viewsVStack

A helicopter is a model built from other pieces, like ContentView. A bag is what @ViewBuilder produces. A manual page is a layout container such as VStack, HStack or ZStack.

5. Initializers and Arguments

swift
Text("Hello")
Image(systemName: "globe")
Circle()

Each line creates a struct by calling an initializer.

  • Arguments may have labels, such as systemName:.
  • Some arguments are unlabeled, such as Text’s string.
  • Empty parentheses call an initializer with no arguments.

6. VStack and Layout

Option-click VStack in Xcode to see its initializer:

swift
init(alignment: HorizontalAlignment = .center,
     spacing: CGFloat? = nil,
     @ViewBuilder content: () -> Content)

VStack is declared as struct VStack<Content> where Content: View, so content must be a function that takes no arguments and returns something that behaves like a View.

swift
VStack(alignment: .leading, spacing: 1) {
    Text("Hello")
    Text("World")
}
  • alignment positions children horizontally. It defaults to .center.
  • spacing is the distance between neighbors in points. Leaving it out uses the platform’s default, which is right in most cases: smaller on Apple Watch, larger on iPhone or visionOS.
  • content supplies the views to arrange.

.leading and .trailing follow the reading direction. They mean left and right in English, and right and left in Arabic or Hebrew, so the layout flows with the text.

Related containers: HStack arranges horizontally; ZStack stacks views on top of each other.

7. Functions as Values

swift
func greetings() -> Text {
    return Text("Greetings!")
}
  • func declares a function, () lists its parameters, and -> Text gives its return type.
  • When a function body is a single expression, return can be left out: { Text("Greetings!") }.
  • The function’s type is () -> Text.

Functions are first-class values, so one can be passed as an argument:

swift
VStack(content: greetings)

greetings names the function; greetings() would call it. () -> Text fits () -> Content because Text is a View.

8. @ViewBuilder

Listing three views in greetings fails:

swift
func greetings() -> Text {
    Image(systemName: "globe")
    Text("Greetings!")
    Circle()
}

A plain function body is a list of statements. The three views are created and thrown away (“Result of ‘Image’ initializer is unused”), and nothing is returned (“Missing return”).

@ViewBuilder changes how the body is read:

swift
@ViewBuilder
func greetings() -> some View {
    Image(systemName: "globe")
    Text("Greetings!")
    Circle()
}
  • It is a result builder: it collects the listed views into one value, a TupleView<(Image, Text, Circle)>, the “bag of Lego”.
  • It supports if and else, so views can be included conditionally.
  • Writing return inside it turns the builder off.
  • The resulting type grows complicated quickly, which is why it is declared as some View.

@ViewBuilder can mark a function, a computed property, or a parameter. VStack’s content parameter is already marked, and so is View’s body requirement. That is why body can list several views or use if without the annotation.

9. Closures and Trailing Closure Syntax

A function can be written inline where it is used. An inline function is a closure.

swift
VStack(content: {
    Text("Hello")
})

When the last argument is a function, it can move outside the parentheses and lose its label:

swift
VStack() {
    Text("Hello")
}

When there are no other arguments, the empty parentheses can go too:

swift
VStack {
    Text("Hello")
}

This is only allowed with a trailing closure. Circle without () is an error, because nothing follows it.

10. Xcode and Modules

Modules. import SwiftUI makes another module’s code available. SwiftUI holds the UI types. Code that is not UI, such as a game’s rules, imports Foundation instead. SwiftData handles persistence.

Previews. #Preview { ContentView() } sets what Xcode shows in the preview canvas. A preview is a visual sanity check, not a UI test.

Documentation. Option-click any symbol to open Quick Help.

Comments. // comments to the end of the line; /* … */ spans lines.

From My Apps

Every idea above already appears in Rhylm, my ambient sound app.

A protocol other than View. The app’s entry point follows the same pattern as a view, with a Scene instead. This version is simplified:

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

The two sides of a contract. The sound catalog’s types declare Equatable. Every stored property is itself Equatable, so the compiler writes == for them:

swift
struct RhylmNoise: Equatable {
    let filename: String
    let nameKey: String
    let fallbackName: String
    let palette: RhylmPalette
}

A computed property outside body. The watch’s audio engine works out the current sound’s name each time it is read:

swift
var currentSoundscapeName: String {
    let current = currentSoundscape
    return NSLocalizedString(current.nameKey, value: current.fallbackName, comment: "Soundscape name")
}

Why some View needs @ViewBuilder. The settings sheet returns a different type on iPad than on iPhone:

swift
@ViewBuilder private var settingsSheet: some View {
    let settings = SettingsView(palette: audioEngine.currentSoundscape.palette)
    if UIDevice.current.userInterfaceIdiom == .pad {
        settings.presentationSizing(.form.fitted(horizontal: false, vertical: true))
    } else {
        settings
    }
}

The two branches have different concrete types, and some View allows only one. @ViewBuilder wraps both branches in a single conditional type, so the property compiles. Without it, the compiler rejects the if.

A container built like VStack. RhylmRegionReader takes a closure of views, just as VStack takes content. This version is simplified:

swift
struct RhylmRegionReader<Content: View>: View {
    @ViewBuilder var content: (GeometryProxy, CGRect) -> Content

    var body: some View {
        GeometryReader { geometry in
            content(geometry, CGRect(origin: .zero, size: geometry.size))
        }
    }
}

<Content: View> is the same constraint as VStack’s where Content: View, and @ViewBuilder on the stored closure lets callers list several views inside it.

Undertide