Start learning free

LESSON 206 OF 292 · PROJECTS: EVERYDAY PROGRAMS

Report Card V5 in Swift: Dictionary of Subjects and Grades

Practice Read the full explanation

Use a dictionary, a loop, and conditionals to print each subject with its letter grade in alphabetical order.

You start with:

var grades = [String: Int]()
grades["Math"] = 92
grades["English"] = 78
grades["Science"] = 85
grades["History"] = 67

Build:

English: C
History: D
Math: A
Science: B

Rules:

  • Visit the subjects in alphabetical order.
  • Look up each subject's score in the dictionary and apply the grading scale (90+ A, 80s B, 70s C, 60s D, else F).
  • On each iteration print the subject, a colon and a space, then the grade, for example English: C.

Use a [String: Int] dictionary and iterate with grades.keys.sorted() - it gives keys in sorted order.

var grades = [String: Int]()
grades["Math"] = 92
grades["English"] = 78
grades["Science"] = 85
grades["History"] = 67

for subject in grades.keys.sorted() {
    let score = grades[subject]!
    var grade = ""
    if score >= 90 {
        grade = "A"
    } else if score >= 80 {
        grade = "B"
    } else if score >= 70 {
        grade = "C"
    } else if score >= 60 {
        grade = "D"
    } else {
        grade = "F"
    }
    print("\(subject): \(grade)")
}

STEP 1 OF 9
    Ctrl + Enter to check

    SWIFT · PROJECTS: EVERYDAY PROGRAMS

    Report Card V5 in Swift, explained

    Problem overview

    The grades now live in a dictionary, grades, that maps each subject name to a score: Math 92, English 78, Science 85 and History 67. The program must print one line per subject, in the form English: C, in alphabetical order of the subject names. It uses the same scale as before: 90 and above is A, 80 to 89 is B, 70 to 79 is C, 60 to 69 is D, anything lower is F.

    For the starting data the output is:

    English: C
    History: D
    Math: A
    Science: B
    

    Approach: sort the keys, then look each one up

    The previous version kept names and scores in two parallel arrays and linked them by position. A dictionary links them directly: the subject is the key, the score is the value, and no position is involved. The grading ladder is the one you already know. What changes is how the loop reaches each score.

    A dictionary promises no particular order. If you loop over grades.keys directly, the lines can come out in any order, and the order can even differ from one run of the program to the next. The lesson needs alphabetical output, so it sorts the keys first: grades.keys.sorted() returns an array of the subject names in ascending order. The loop walks that array and, for each subject, asks the dictionary for its score.

    Step by step

    1. Loop over the sorted keys. for subject in grades.keys.sorted() hands you one subject name at a time, from "English" to "Science". Write the closing brace right away and put the other steps inside.
    2. Look up the score. grades[subject] finds the value stored under that key. Add ! to the end, for a reason explained below.
    3. Declare var grade = "". It is a var because the ladder assigns it.
    4. Build the ladder. Start with if score >= 90 for A, then else if tests for 80, 70 and 60, and a final else for F. Each test relies on the higher ones having failed, so each needs only a lower bound.
    5. Print inside the loop, after the ladder: the subject, a colon and a space, then the grade.

    The solution in Swift

    var grades = [String: Int]()
    grades["Math"] = 92
    grades["English"] = 78
    grades["Science"] = 85
    grades["History"] = 67
    
    for subject in grades.keys.sorted() {
        let score = grades[subject]!
        var grade = ""
        if score >= 90 {
            grade = "A"
        } else if score >= 80 {
            grade = "B"
        } else if score >= 70 {
            grade = "C"
        } else if score >= 60 {
            grade = "D"
        } else {
            grade = "F"
        }
        print("\(subject): \(grade)")
    }
    

    Swift specifics worth knowing:

    • The type [String: Int]. It is a dictionary with String keys and Int values. [String: Int]() creates an empty one, and grades["Math"] = 92 adds an entry, or replaces the value if the key already exists. That is why the dictionary is declared with var.
    • A lookup returns an optional. A key may be missing, so grades["Math"] has the type Int?: it prints as Optional(92), and grades["Music"] is nil. The ! unwraps it and says "a value is definitely there". Here that is true, because subject came from the dictionary's own keys.
    • ! on a nil stops the program. If you wrote grades["Music"]!, a subject that is not in the dictionary, the program would crash at run time. Use ! only when the key is certain to exist.
    • keys.sorted() returns an array. grades.keys is not an array and can't be indexed. sorted() gives a new [String], and the dictionary itself is unchanged.
    • Strings sort by character code. Uppercase letters come before lowercase ones, so ["math", "Zoology", "Art"].sorted() is ["Art", "Zoology", "math"]. With names that all start with a capital letter, as here, this is plain alphabetical order.

    Why the sort is needed

    Looping over the keys without sorting prints the same four subjects, but in an order you can't rely on. Two runs of the same program on this data printed the keys as Science, History, Math, English and as Math, History, Science, English. The data is identical; only the order differs. Sorting the keys makes the output the same every time, and that is also what the lesson's tests expect.

    Edge cases and common mistakes

    • Boundaries. Scores of exactly 90, 80, 70 and 60 belong to the higher grade, so each test uses >=. With Art: 90, Biology: 80, Chem: 70, Gym: 60 and Music: 59 the program prints A, B, C, D and F, in the order Art, Biology, Chem, Gym, Music.
    • An empty dictionary. There are no keys, the loop body never runs, and nothing is printed.
    • Looping without sorted(). The output has the right lines in an order that can change from run to run, so it can't match the expected output reliably.
    • Forgetting the !. Without it score is an Int?, and the comparison score >= 90 is a compile error: value of optional type 'Int?' must be unwrapped to a value of type 'Int'.
    • Mixed-case names. A subject written as "math" sorts after every capitalized name. Keep the names consistent if alphabetical order matters.

    Testing

    These outputs come from running the solution on other dictionaries.

    • ["Art": 90, "Music": 59, "Gym": 60, "Biology": 80, "Chem": 70] prints Art: A, Biology: B, Chem: C, Gym: D and Music: F.
    • ["math": 95, "Zoology": 88, "Art": 71] prints Art: C, Zoology: B and math: A.
    • An empty dictionary prints nothing.

    Try changing a score in the editor above and see which line changes.

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