Start learning free

LESSON 598 OF 640 · OBJECT-ORIENTED PROGRAMMING

Secret PIN in Swift

Practice

You build the class Phone. It keeps a secret PIN and counts the wrong tries.

Both values are private. Other code can't read or change them. It can only call the methods below.

  • Phone(pin) makes a phone with that PIN and no wrong tries.
  • isLocked() returns true after 3 wrong tries. Before that, it returns false.
  • unlock(attempt) returns true when attempt is the PIN.
  • Any other attempt returns false. It counts as one more wrong try.
  • A locked phone stays locked for good. Then unlock always returns false, even with the right PIN.
  • The right PIN doesn't reset the count of wrong tries.

Make both fields private the way the Access Modifiers lesson does in Swift. In Python the names start with an underscore. In JavaScript they start with #.

The starter code spells the methods your language's way. Python has is_locked. C# has Unlock and IsLocked.

Each test case makes one phone with the given PIN. Then it calls the methods in order. The output line shows each answer as True or False.

 

Example 1:

Input:
    pin = "1234"
    unlock("1111")
    unlock("1234")
    isLocked()
Output: False True False
Explanation: "1111" is wrong. That is 1 wrong try.
"1234" is the PIN, so the phone opens.
1 wrong try doesn't lock the phone.

Example 2:

Input:
    pin = "0042"
    unlock("4200")
    unlock("0000")
    unlock("0041")
    isLocked()
    unlock("0042")
Output: False False False True False
Explanation: Three wrong tries lock the phone.
After that, even the right PIN "0042" gets False.

Example 3:

Input:
    pin = "7777"
    unlock("1234")
    unlock("7777")
    unlock("0000")
    unlock("7777")
    unlock("9999")
    isLocked()
Output: False True False True False True
Explanation: The right PIN works twice.
It doesn't reset the count.
"9999" is the third wrong try, so the phone locks.

 

Constraints:

  • Each PIN has exactly 4 digits.
  • Each attempt has exactly 4 digits too.
  • A PIN can start with 0, like "0042".
  • 1 to 1000 calls per phone.
STEP 1 OF 6
    Ctrl + Enter to check

    Secret Pin in Swift

    Keep going with Swift500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free