Start learning free

LESSON 197 OF 292 · PROJECTS: EVERYDAY PROGRAMS

Password Strength V2 in Swift: Has a Digit with a for-in Loop

Practice Read the full explanation

Extend the length check with a second rule: the password must also contain at least one digit.

You start with:

let password = "Secret99"

Build:

Length: 8
Has digit: True
Strong

Rules:

  • Print "Length: " followed by the number of characters.
  • Loop through each character to set a boolean flag hasDigit, which starts as false and becomes true when a digit is seen.
  • Print "Has digit: " followed by the flag. Write it as True or False with a capital letter, exactly as in the example (your language's own boolean prints differently, so choose the text yourself).
  • If the length is at least 8 and hasDigit is true, print Strong; otherwise print Weak.

Try other passwords: with abcdefgh the output is

Length: 8
Has digit: False
Weak

character.isNumber tests a single character. Use (hasDigit ? "True" : "False") to print a capitalised True/False.

let password = "Secret99"

let length = password.count
print("Length: \(length)")
var hasDigit = false
for character in password {
    if character.isNumber {
        hasDigit = true
    }
}
print("Has digit: \(hasDigit ? "True" : "False")")
if length >= 8 && hasDigit {
    print("Strong")
} else {
    print("Weak")
}

STEP 1 OF 8
    Ctrl + Enter to check

    SWIFT · PROJECTS: EVERYDAY PROGRAMS

    Password Strength V2 in Swift, explained

    Problem overview

    The checker gets a second rule. A password is strong only if it has at least 8 characters and contains at least one digit. The starter is let password = "Secret99", and the program prints three lines: the length, whether a digit was found, and the verdict.

    Length: 8
    Has digit: True
    Strong

    The verdict is Strong when both rules pass and Weak otherwise. For "abcdefgh" the output is Length: 8, Has digit: False and Weak. The boolean is printed as True and False with a capital letter, which is not how Swift prints a Bool by default.

    Approach: a flag set by a loop

    The length check from the previous version stays. The new part is "is there a digit anywhere in the text?", and the way to answer it is a flag. Start with hasDigit = false, look at every character, and set the flag to true when one of them is a digit. The loop never sets the flag back to false, so one digit anywhere is enough, however many non-digits come after it.

    When the loop ends, the flag holds the answer, and the verdict combines the two rules with &&: both must be true.

    This is the usual shape of a "does any element have this property?" question: a flag that starts false, one pass over the data, and a test that can only raise the flag. The same pattern works for any property of a text or a list.

    Step by step

    1. Store the length in a constant: password.count. It is used twice, in the printed line and in the 8-character rule.
    2. Print Length: followed by the number, using string interpolation.
    3. Create the flag. var hasDigit = false: it is a var, because it changes, and it starts as false because no digit has been seen yet.
    4. Loop over the characters. for character in password gives one Character per pass, from the first to the last.
    5. Test each character. Inside the loop, an if checks character.isNumber and sets hasDigit to true when the test passes.
    6. Print the flag after the loop. It must be outside the braces, so it runs once, when every character has been checked. The ternary hasDigit ? "True" : "False" inside the interpolation chooses the text.
    7. Write the verdict's if: length >= 8 && hasDigit prints Strong.
    8. Add the else: everything else prints Weak, whether the password was too short, had no digit or both.

    The solution in Swift

            let password = "Secret99"
    
            let length = password.count
            print("Length: \(length)")
            var hasDigit = false
            for character in password {
                if character.isNumber {
                    hasDigit = true
                }
            }
            print("Has digit: \(hasDigit ? "True" : "False")")
            if length >= 8 && hasDigit {
                print("Strong")
            } else {
                print("Weak")
            }
    

    Details specific to Swift:

    • A String is a sequence of Character values. That is why for character in password works directly, with no indexing and no conversion to an array.
    • Booleans print in lowercase. print("Has digit: \(hasDigit)") would print Has digit: true. The lesson's output uses a capital, so the ternary operator condition ? a : b picks one of two strings instead. Quotes inside an interpolation are allowed in Swift 5 and later, which is what lets the ternary sit inside the string literal.
    • isNumber is broader than "0 to 9". It is true for every character Unicode classes as a number, and that includes characters such as ½, ² and ٣. With "abcdefg½" the lesson's solution prints Has digit: True and Strong. Swift's isWholeNumber is narrower: it is false for ½ but true for ² and ٣, so it is not the same as "an ASCII digit" either. For ordinary passwords of letters, 0 to 9 and symbols, isNumber does what the lesson needs.
    • && short-circuits. If length >= 8 is false, Swift doesn't evaluate the right side. With plain Boolean variables it makes no visible difference here.
    • The loop variable is a constant. character is a new constant on each pass, so the body can read it but can't assign to it.

    Edge cases and common mistakes

    • A digit in the middle or at the end. The flag doesn't care where the digit is. A digit at the start, in the middle or at the end sets it.
    • Resetting the flag in the loop. An else { hasDigit = false } would let the last character overwrite the answer, so a password ending in a letter would report no digit. The flag only ever changes in one direction.
    • Printing the flag inside the loop. That prints one Has digit: line per character instead of one line at the end.
    • Short but with a digit. "Abc1" has a length of 4 and Has digit: True, but the verdict is Weak, because both rules are required.
    • Long but without a digit. "abcdefgh" passes the length rule and fails the digit rule, so it is Weak too.
    • Using || instead of &&. That would call a password strong when only one rule passes.
    • Declaring the flag with let. A constant can't be assigned inside the loop, so the compiler reports an error.

    Testing

    Change password in the editor. These outputs come from the reference solution:

    • "abcdefgh" prints Length: 8, Has digit: False and Weak.
    • "12345678" prints Length: 8, Has digit: True and Strong.
    • "Abc1" prints Length: 4, Has digit: True and Weak.
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free