user6692600 user6692600 - 3 months ago 8
iOS Question

Counter property does not change value

I am making a quiz in the Swift Playgrounds app and I want to keep a counter of the number of correct answers. The value of

correct
doesn't change, and I don't know why.

var correct:Int = 0
func qa(question: String, answer: String) {
show(question)
var ans = ask("answer")
if (ans.lowercased() == answer) {
show("correct")
correct = correct + 1
} else {
show("wrong you numpty!")
}
}
func qaor(question: String, answer: String, answer2: String) {
show(question)
var ans = ask("answer")
if (ans.lowercased() == answer) || (ans.lowercased() == answer2) {
show("correct")
correct = correct + 1
} else {
show("wrong you numpty!")
}
}


show("What is your name?")

let name = ask("Name")

show("Hi " + name)

qa(question: "What is the name of the character played by Simon Jones in the Hitchikers Guide to the Galaxy?", answer: "arthur dent")

qaor(question: "What is voiced by Peter Jones in the Hitchikers Guide to the Galaxy?", answer: "the book", answer2: "the guide")

qa(question: "finish this sentence .doing the coastlines was always my Favourite, the rough crinkley edges, .... ", answer: "fjords")

var cf = "no"
if (correct == 0) {
var cf = "no"
} else if (correct == 1) {
var cf = "one"
} else if (correct == 2) {
var cf = "two"
} else if (correct == 3) {
var cf = "three"
}

show("you got " + cf + " questions correct out of three")

Answer

Do not declare the cf variable for every if/else statement. It creates a local variable and you aren't changing the first cf.

Instead, try this:

var cf = "no"
if (correct == 0) {
    cf = "no"
} else if (correct == 1) {
    cf = "one"
} else if (correct == 2) {
    cf = "two"
} else if (correct == 3) {
    cf = "three" 
}

show("you got " + cf + " questions correct out of three")
Comments