Menu
Coddy logo textTech

Summary Report

Part of the Logic & Flow section of Coddy's Swift journey — lesson 53 of 56.

Final feature: instead of one category, run the whole quiz and produce a per-category summary at the end.

You'll lean on every chapter at once: tuple destructuring for the iteration, lenient grading from the strings chapter, default-subscript dictionaries from the dictionaries chapter, sorted iteration for deterministic output.

Build the per-category counters as two parallel dictionaries:

var totals: [String: Int] = [:]
var rights: [String: Int] = [:]

Increment totals[cat, default: 0] += 1 for every question; increment rights[cat, default: 0] only on a correct answer. At the end, walk the categories in alphabetical order to print the report.

challenge icon

Challenge

Medium

The same six-question bank from the previous lesson. Read six answers from stdin, one per line, in the same order as the bank. Use lenient grading.

Print, in this order:

  1. One line per category, sorted alphabetically, in the format <category>: <right>/<total>
  2. One final line: Total: <right>/<total> across the whole run

For input 4 / 3.14 / Paris / Atlantic / green / WATER, the output is:

geo: 1/2
math: 2/2
science: 2/2
Total: 5/6

Cheat sheet

Use two parallel dictionaries to track per-category scores:

var totals: [String: Int] = [:]
var rights: [String: Int] = [:]

// For each question with category cat:
totals[cat, default: 0] += 1
// On correct answer:
rights[cat, default: 0] += 1

Walk categories in alphabetical order using sorted() for deterministic output:

for cat in totals.keys.sorted() {
    let r = rights[cat, default: 0]
    let t = totals[cat]!
    print("\(cat): \(r)/\(t)")
}

Compute totals across all categories by summing dictionary values:

let totalRight = rights.values.reduce(0, +)
let totalAll = totals.values.reduce(0, +)
print("Total: \(totalRight)/\(totalAll)")

Try it yourself

let questions: [(String, String, String)] = [
    ("math", "2 + 2?", "4"),
    ("math", "Value of pi to 2 decimals?", "3.14"),
    ("geo", "Capital of France?", "Paris"),
    ("geo", "Largest ocean?", "Pacific"),
    ("science", "Color of grass?", "green"),
    ("science", "H2O is?", "water")
]

// TODO: read 6 answers; lenient grade; build per-category totals/rights;
// print sorted summary lines + Total
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow