Menu
Coddy logo textTech

Lenient Grading

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

Strict equality is harsh. Real quizzes accept paris, Paris, and PARIS as the same answer.

The recipe from chapter 1: trim whitespace, lowercase both sides, compare:

func grade(_ given: String, _ answer: String) -> Bool {
    let g = given.trimmingCharacters(in: .whitespaces).lowercased()
    let a = answer.trimmingCharacters(in: .whitespaces).lowercased()
    return g == a
}

This is the kind of helper that's worth pulling out into its own function. The quiz loop reads cleaner with one line per question, and tomorrow's bug fix happens in one place.

challenge icon

Challenge

Easy

Define a function grade(_ given: String, _ answer: String) -> Bool that returns true when the two strings match after trimming whitespace and lowercasing both sides.

The questions bank is given. Read three lines from stdin. Print, for each question:

  1. The question text
  2. correct or wrong based on the lenient comparison

After the run, print Score: <n>/3.

For input 4 / PARIS / Green, the output is:

2 + 2?
correct
Capital of France?
correct
Color of grass?
correct
Score: 3/3

Cheat sheet

Lenient string comparison: trim whitespace and lowercase both sides before comparing.

func grade(_ given: String, _ answer: String) -> Bool {
    let g = given.trimmingCharacters(in: .whitespaces).lowercased()
    let a = answer.trimmingCharacters(in: .whitespaces).lowercased()
    return g == a
}

Try it yourself

let questions: [(String, String, String)] = [
    ("math", "2 + 2?", "4"),
    ("geo", "Capital of France?", "Paris"),
    ("science", "Color of grass?", "green")
]

// TODO: func grade(_:_:)->Bool with trim + lowercase compare
// then loop, print question, read answer, print correct/wrong;
// finish with 'Score: <n>/3'
quiz iconTest yourself

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

All lessons in Logic & Flow