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
- 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. - Look up the score.
grades[subject]finds the value stored under that key. Add!to the end, for a reason explained below. - Declare
var grade = "". It is avarbecause the ladder assigns it. - Build the ladder. Start with
if score >= 90for A, thenelse iftests for 80, 70 and 60, and a finalelsefor F. Each test relies on the higher ones having failed, so each needs only a lower bound. - 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 withStringkeys andIntvalues.[String: Int]()creates an empty one, andgrades["Math"] = 92adds an entry, or replaces the value if the key already exists. That is why the dictionary is declared withvar. - A lookup returns an optional. A key may be missing, so
grades["Math"]has the typeInt?: it prints asOptional(92), andgrades["Music"]isnil. The!unwraps it and says "a value is definitely there". Here that is true, becausesubjectcame from the dictionary's own keys. !on anilstops the program. If you wrotegrades["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.keysis 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
>=. WithArt: 90,Biology: 80,Chem: 70,Gym: 60andMusic: 59the 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 itscoreis anInt?, and the comparisonscore >= 90is 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]printsArt: A,Biology: B,Chem: C,Gym: DandMusic: F.["math": 95, "Zoology": 88, "Art": 71]printsArt: C,Zoology: Bandmath: A.- An empty dictionary prints nothing.
Try changing a score in the editor above and see which line changes.
