import SwiftUI
struct OptionalUnwrappingDemo: View {
@State private var name: String? = nil
@State private var greeting: String = ""
var body: some View {
VStack(spacing: 20) {
Text("Optional Unwrapping")
.font(.title)
.bold()
TextField("Enter your name", text: Binding(
get: { name ?? "" },
set: { name = $0.isEmpty ? nil : $0 }
))
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding(.horizontal)
Button("Show Greeting") {
if let unwrappedName = name, !unwrappedName.isEmpty {
greeting = "Hello, \(unwrappedName)!"
} else {
greeting = "Please enter your name."
}
}
.buttonStyle(.borderedProminent)
Text(greeting)
.font(.headline)
.foregroundColor(.blue)
.padding()
Spacer()
}
.padding()
}
}
struct OptionalUnwrappingDemo_Previews: PreviewProvider {
static var previews: some View {
OptionalUnwrappingDemo()
}
}We use a TextField bound to an optional String? by creating a custom Binding that converts empty strings to nil and vice versa. When the user taps the button, we safely unwrap the optional using if let. If the name exists and is not empty, we show a greeting message. Otherwise, we prompt the user to enter their name. This demonstrates safe unwrapping of optionals to avoid crashes and handle missing data gracefully.