Swift and SwiftUI Foundations
1. Structures and Protocols
struct ContentView: View {
var body: some View {
Text("Hello")
}
}structdeclares a structure, a value type.ContentViewis the structure’s name.: Viewdeclares conformance to theViewprotocol:ContentViewbehaves like aView.- 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 implementvar body: some View. - Reward. Once it does, it gains everything
Viewoffers, including hundreds of view modifiers such as.padding()and.foregroundStyle(_:), which are defined in protocol extensions onView.
2. Variables and the Type System
var i: Int = 0
let number = 10vardeclares a mutable variable;letdeclares an immutable constant.: Intgives the type;= 0gives an initial value.IntandStringare 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.
let number = 10number 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:
struct Greeting: View {
var count: Int = 0
var name: String
var body: some View {
Text("Hello, \(name)")
}
}
Greeting(name: "Swift")- A default value, like
count. - No default, like
name. Then whoever creates the struct must supply it. Swift generates a memberwise initializer, soGreeting(name: "Swift")is the only way to make one. - A custom initializer (
init) that assigns it.
Optionals. Absence is a type, not a missing value.
var number: Int? = nilInt? is Optional<Int>: either a wrapped Int or nil.
3. Computed Properties and some View
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
bodyneeds 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.
| Lego | SwiftUI | Example |
|---|---|---|
| Brick | Basic view | Text, Circle |
| Helicopter | Custom view | MyView |
| Bag | Holds views | TupleView |
| Manual | Arranges views | VStack |
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
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:
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.
VStack(alignment: .leading, spacing: 1) {
Text("Hello")
Text("World")
}alignmentpositions children horizontally. It defaults to.center.spacingis 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.contentsupplies 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
func greetings() -> Text {
return Text("Greetings!")
}funcdeclares a function,()lists its parameters, and-> Textgives its return type.- When a function body is a single expression,
returncan be left out:{ Text("Greetings!") }. - The function’s type is
() -> Text.
Functions are first-class values, so one can be passed as an argument:
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:
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:
@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
ifandelse, so views can be included conditionally. - Writing
returninside 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.
VStack(content: {
Text("Hello")
})When the last argument is a function, it can move outside the parentheses and lose its label:
VStack() {
Text("Hello")
}When there are no other arguments, the empty parentheses can go too:
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:
@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:
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:
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:
@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:
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.