Bird
0
0

What will happen when this SwiftUI code runs?

medium📝 Predict Output Q5 of 15
iOS Swift - User Input and Forms
What will happen when this SwiftUI code runs?
struct ContentView: View {
  @State private var date = Date()
  var body: some View {
    DatePicker("Pick a date", selection: $date, displayedComponents: .date)
    Text("Date: \(date, formatter: DateFormatter())")
  }
}
AShows a date picker and text with the current date formatted
BShows a date picker but text shows an empty string
CCompilation error due to missing DateFormatter setup
DDatePicker shows time instead of date
Step-by-Step Solution
Solution:
  1. Step 1: Check DateFormatter usage

    DateFormatter() with no dateStyle, timeStyle, or dateFormat set returns an empty string for dates.
  2. Step 2: Understand SwiftUI text interpolation with formatter

    The Text displays "Date: " followed by empty string from the unconfigured formatter.
  3. Final Answer:

    Shows a date picker but text shows an empty string -> Option B
  4. Quick Check:

    Unconfigured DateFormatter = empty string [OK]
Quick Trick: Always configure DateFormatter with style or format before using in Text [OK]
Common Mistakes:
  • Using default DateFormatter() without setup
  • Expecting automatic formatting
  • Ignoring formatter parameter

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes