Hello I am trying to implement use of Radio buttons. After days of trying to get the values of my radio buttons (that is to see which one is checked and save value) I have had no success:
Here is my code:
var qValueNumbers = [0]
let totalSum = Int()
@IBAction func calcGroupScore(_ sender: NSButton) {
answerItem = ""
for item in results {
if let record = item.value(forKey: "answer") as? String {
answerItem.append(record)
answerLabel.stringValue = answerItem
print ("Answer is \(answerItem)")
if let record = item.value(forKey: "qValue") as? String, var theValue = Int(record) {
// groupScoreLabel.stringValue = qValueItem
print ("qValueNumbers before append", qValueNumbers)
func getScore (){
if (oneRadioButton != nil) && distractor1 == answerItem {
print("button1 Selected")
qValueNumbers.append(theValue)
}
if (twoRadioButton != nil) && distractor2 == answerItem {
print("button2 Selected")
qValueNumbers.append(theValue)
}
if (threeRadioButton != nil) && distractor3 == answerItem {
print("button3 Selected")
qValueNumbers.append(theValue)
}
if (fourRadioButton != nil) && distractor4 == answerItem {
print("button4 Selected")
qValueNumbers.append(theValue)
}
if (fiveRadioButton != nil) && distractor5 == answerItem {
print("button5 Selected")
qValueNumbers.append(theValue)
}
else{
// qValueNumbers.append(0)
print ("The value of qValue is \(theValue)")
}
}
getScore()
qValueNumbers.append(theValue)
let totalSum = qValueNumbers.reduce(0, +)
print ("qValue is \(theValue)")
print ("qValueNumbers after append", qValueNumbers)
print ("Total is \(totalSum)")
print ("Group score is \(totalSum)")
}
}
}
Here is my log output:
Answer is 3
qValueNumbers before append [0, 1530, 2650]
The value of qValue is 2650
qValue is 2650
qValueNumbers after append [0, 1530, 2650, 2650]
Total is 6830
Group score is 6830
Here is the problem:
Whether or not a button is selected the "qValue" is still appended to qValueNumbers". If a radio button between 1 and 5 is selected and that button is the correct answer, then the qValue should be appended. As of now regardless of whether the checked button matches the correct answer a qValue is still appended instead of "0".
Any help will nbe appreciated.
Great.
You're right, to begin, it may be good to write a bit verbose but easy to understand code.
But, in that case, it is better to make names very explicit, such as recordAnswer vs record only.
Clearly, if distriX were not defined, it could never match.
So, that answers a previous question: does buttonX selected ever gets printed ?
If no (that was the case), that means that your test failed for some reason (the one you found).
Anyway, good continuation you can now close the thread.