Bird
0
0

You want to show a label with text "No messages" only when the messages array is empty. Which SwiftUI code correctly handles this empty state?

hard📝 Application Q15 of 15
iOS Swift - Lists and Data Display
You want to show a label with text "No messages" only when the messages array is empty. Which SwiftUI code correctly handles this empty state?
Aif messages.count > 0 { Text("No messages") } else { List(messages, id: \.self) { Text($0) } }
BList(messages, id: \.self) { Text($0) } always shows, no empty state
CText(messages.isEmpty ? "No messages" : "")
Dif messages.isEmpty { Text("No messages") } else { List(messages, id: \.self) { Text($0) } }
Step-by-Step Solution
Solution:
  1. Step 1: Understand the requirement

    Show "No messages" label only when messages array is empty, otherwise show the list.
  2. Step 2: Evaluate options

    if messages.isEmpty { Text("No messages") } else { List(messages, id: \.self) { Text($0) } } uses if messages.isEmpty to conditionally show the label or the list, which is correct.
  3. Step 3: Check other options

    if messages.count > 0 { Text("No messages") } else { List(messages, id: \.self) { Text($0) } } reverses the condition incorrectly. Text(messages.isEmpty ? "No messages" : "") shows empty text instead of list. List(messages, id: \.self) { Text($0) } always shows, no empty state never shows empty state.
  4. Final Answer:

    if messages.isEmpty { Text("No messages") } else { List(messages, id: \.self) { Text($0) } } -> Option D
  5. Quick Check:

    Use if isEmpty to toggle empty state UI [OK]
Quick Trick: Use if isEmpty to show empty state or data list [OK]
Common Mistakes:
  • Reversing the condition logic
  • Showing empty text instead of list
  • Not handling empty state at all

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes