Let's think about this for a moment
Optionals (`?`, `if let`, `guard let`) are used constantly in iOS development — they're crucial for protecting against crashes in scenarios like API responses or user input, where a value 'may or may not' be there. You'll see Closures (`{ ... }`) used for button actions and list transformations. You'll use Structs (`struct Todo { var title: String; var isDone: Bool = false }`) to represent your app's data models (a todo item, a user profile) — even SwiftUI Views are structs (not classes) — that's an intentional design choice for performance.
Let's connect this to a real-world scenario
Writing `var name: String? = nil` tells the compiler that 'name' could be nil — writing `guard let unwrappedName = name else { return }` makes the function early-return if name is nil, protecting against a crash. You'll see button actions written with trailing closure syntax, like `Button("Save") { print("saved") }`, again and again once we get to SwiftUI (next lesson).
Let's look at it together
// Optional safety
var name: String? = nil
func greet() {
guard let unwrappedName = name else {
print("No name provided")
return
}
print("Hello, \(unwrappedName)!")
}
// Struct — will represent our UI data later
struct TodoItem: Identifiable {
let id = UUID()
var title: String
var isDone: Bool = false
}$ greet()
No name providedTry it in 5 minutes
Write your own `TodoItem` struct, create 2-3 instances of it, and check the `print` output in an Xcode Playground.
A quick word of caution
Keep in mind that `!` is basically saying 'I'm forcing this to be treated as non-nil even though it could be nil' — if it actually turns out to be nil, your app will crash immediately.