Menu
Coddy logo textTech

Ask Questions

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

The first feature: ask every question in order and print whether each answer was right.

The question bank is hardcoded for this lesson, the player's answers come from stdin (one per line, in order).

let questions: [(String, String, String)] = [
    ("math", "2 + 2?", "4"),
    ("geo", "Capital of France?", "Paris")
]
for (_, text, answer) in questions {
    print(text)
    let given = readLine()!
    print(given == answer ? "correct" : "wrong")
}

Read top to bottom: print the question, read one line, compare. The next lesson softens that strict comparison so it doesn't fail on capitalisation or stray whitespace.

challenge icon

Challenge

Easy

The questions bank is given. Read three lines from stdin (the player's answers, in order). For each question, print:

  1. The question text on its own line
  2. correct when the given answer is exactly equal to the stored answer, otherwise wrong

After all three questions, print Score: <n>/3 with the count of correct answers.

For input 4 / Paris / red, the output is:

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

Cheat sheet

Iterate over a tuple array of questions, read answers from stdin, and compare:

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

var score = 0
for (_, text, answer) in questions {
    print(text)
    let given = readLine()!
    if given == answer {
        print("correct")
        score += 1
    } else {
        print("wrong")
    }
}
print("Score: \(score)/\(questions.count)")

Try it yourself

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

// TODO: for each question, print text, read answer, print correct/wrong;
// then print '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