2016-08-08 2 views
-1

Я делаю викторину в приложении Swift Playgrounds, и я хочу сохранить счетчик количества правильных ответов. Значение correct не меняется, и я не знаю почему.Свойство счетчика не меняет значение

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") 
+0

Не повторно объявить 'cf' в вашей, если-иначе блок. просто сделайте 'cf =" no "' и т. д. – Macondo2Seattle

+0

Пожалуйста, отформатируйте и отстудите свой код по крайней мере в соответствии с * некоторым * руководством по стилю. Этот код нечитабелен и не относится к StackOverflow. –

ответ

5

Не объявлять переменную cf для каждого, если/другого заявления. Он создает локальную переменную, и вы не меняете первый cf.

Вместо этого, попробуйте следующее:

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") 
+0

Спасибо, berksy92 Я только что протестировал его, и он работает – Catmantj

Смежные вопросы