Start learning free

LESSON 200 OF 292 · PROJECTS: EVERYDAY PROGRAMS

Password Strength V5 in Swift: Common Password Check with a Set

Practice Read the full explanation

Use a dictionary (or set) as a fast lookup table to reject well-known weak passwords.

You start with:

let common: Set<String> = ["password", "123456", "qwerty", "letmein"]
let password = "qwerty"

Build:

Password: qwerty
Common: True
Weak: reject

Rules:

  • Print "Password: " followed by the password.
  • Look the password up in the set common and store the result as a boolean.
  • Print "Common: " followed by the boolean. 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 it is common, print "Weak: reject"; otherwise print "Strong: accept".

Try other passwords: with Tr0ub4dor the output is

Password: Tr0ub4dor
Common: False
Strong: accept

Use a Set<String> literal and call .contains(password).

let common: Set<String> = ["password", "123456", "qwerty", "letmein"]
let password = "qwerty"

print("Password: \(password)")
let isCommon = common.contains(password)
print("Common: \(isCommon ? "True" : "False")")
if isCommon {
    print("Weak: reject")
} else {
    print("Strong: accept")
}

STEP 1 OF 5
    Ctrl + Enter to check

    SWIFT · PROJECTS: EVERYDAY PROGRAMS

    Password Strength V5 in Swift, explained

    Problem overview

    Some passwords are weak whatever they contain, because everyone tries them first. This version rejects those. You start with a set of well-known passwords, common, and the password to check:

    let common: Set<String> = ["password", "123456", "qwerty", "letmein"]
    let password = "qwerty"

    The program prints the password, then whether it is in the set, then a verdict. A common password gets Weak: reject and any other gets Strong: accept:

    Password: qwerty
    Common: True
    Weak: reject

    For "Tr0ub4dor" the output is Password: Tr0ub4dor, Common: False and Strong: accept. Nothing in this version looks at length or character classes: the only question is whether the exact text is in the list.

    Approach: a set as a lookup table

    Checking membership in a plain array means comparing the password with every element until one matches, and the time grows with the size of the list. A real list of common passwords can hold millions of entries. A set is built for the question "is this value in here?": it answers in constant time on average, however many values it holds. That makes it the right container whenever you only need to ask whether something is present and don't care about order or positions.

    The program asks the question once, stores the answer as a Bool and uses it twice: to print the Common line and to choose the verdict.

    Step by step

    1. Print the password. print("Password: \(password)") shows which password is being checked.
    2. Look it up. let isCommon = common.contains(password). The contains method of a set returns true when the set holds that text.
    3. Print the Common line. Swift prints a Bool in lowercase, and the output needs a capital letter, so isCommon ? "True" : "False" inside the interpolation picks the text.
    4. Write the if on isCommon. A common password is rejected whatever else is true of it, so its body prints Weak: reject.
    5. Add the else. The } that closes the if also opens the else, and its body prints Strong: accept.

    The solution in Swift

            let common: Set<String> = ["password", "123456", "qwerty", "letmein"]
            let password = "qwerty"
    
            print("Password: \(password)")
            let isCommon = common.contains(password)
            print("Common: \(isCommon ? "True" : "False")")
            if isCommon {
                print("Weak: reject")
            } else {
                print("Strong: accept")
            }
    

    Swift details here:

    • The type annotation matters. A bare array literal in ["password", ...] would make an Array. Writing : Set<String> tells Swift to build a set from the same literal. Without the annotation, common would be an array, and an array's contains would still compile and work, just with a linear search.
    • contains returns a Bool. It gives a plain true or false, and so needs no optional handling. That differs from a dictionary lookup, which returns an optional.
    • A Bool can be used directly as a condition. if isCommon { is enough. Writing if isCommon == true is legal and means the same, but the shorter form is idiomatic.
    • The ternary inside the interpolation. \(isCommon ? "True" : "False") places a conditional expression inside a string literal. The inner quotes are allowed in Swift 5.
    • Sets are unordered. Printing a whole set can list the values in any order, and the order can change between runs. This program never prints the set, only asks whether a value is in it.

    Edge cases and common mistakes

    • Case matters. "Qwerty" isn't in the set, so it prints Common: False and Strong: accept. Matching ignoring case would take a further step, such as lowercasing the password before the lookup, which this version doesn't ask for.
    • The empty string. It isn't in the set, so the output is Password: , then Common: False and Strong: accept. This version doesn't check the length.
    • Not being common doesn't mean strong. The verdict word Strong: accept only says that the password is not on the list. The checks from earlier versions are separate rules.
    • Looping to search. A for loop over the set that compares each element does the same job, with more code and a slower search for large sets. contains says it in one call.
    • Printing the Bool as it is. "Common: \(isCommon)" prints true in lowercase, which doesn't match the required text.
    • Typing the set as an array. If a learner leaves out the Set<String> annotation, the code still compiles and prints the same text for small inputs, so the mistake only costs speed.

    Testing

    Change password in the editor. The outputs below are those of the reference solution:

    • "Tr0ub4dor" prints Password: Tr0ub4dor, Common: False and Strong: accept.
    • "Qwerty" prints Password: Qwerty, Common: False and Strong: accept.
    • "" prints Password: , Common: False and Strong: accept.
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free