Bird
0
0

You want to use a repeat-while loop to ask a user for a password until they enter "swift123". Which code snippet correctly implements this?

hard📝 Application Q15 of 15
Swift - Loops
You want to use a repeat-while loop to ask a user for a password until they enter "swift123". Which code snippet correctly implements this?
Arepeat { print("Enter password:") input = readLine() ?? "" } while input == "swift123"
Bvar input = "" while input != "swift123" { print("Enter password:") input = readLine() ?? "" }
Cvar input = "" repeat { print("Enter password:") input = readLine() ?? "" } while input != "swift123"
Dvar input = "" repeat { input = readLine() ?? "" } while input != "swift123" print("Enter password:")
Step-by-Step Solution
Solution:
  1. Step 1: Understand the requirement

    The loop must ask for password at least once and repeat until the user enters "swift123".
  2. Step 2: Check each option

    var input = "" repeat { print("Enter password:") input = readLine() ?? "" } while input != "swift123" uses repeat-while, asks inside loop, and repeats while input is not "swift123". This matches the requirement.
    var input = "" while input != "swift123" { print("Enter password:") input = readLine() ?? "" } uses while loop, which may skip asking if input is already "swift123".
    repeat { print("Enter password:") input = readLine() ?? "" } while input == "swift123" repeats while input equals "swift123", which is opposite of requirement.
    var input = "" repeat { input = readLine() ?? "" } while input != "swift123" print("Enter password:") prints prompt after loop ends, so user is not prompted before input.
  3. Final Answer:

    var input = "" repeat { print("Enter password:") input = readLine() ?? "" } while input != "swift123" -> Option C
  4. Quick Check:

    Repeat-while asks first, repeats until correct [OK]
Quick Trick: Use repeat-while to ask first, then check condition [OK]
Common Mistakes:
  • Using while loop that may skip first prompt
  • Reversing condition logic
  • Prompting outside the loop

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes