I'm trying to get the count of value from a key,value
pairs of a [String: Any]
dictionary
for item in mainData {
var answerDict = [String: Any]()
var totalCountValOne = 0
for (key,value) in item.extraAnswers {
if key.contains("correct") {
answerDict[key] = value
}
}
for (key,value) in answerDict {
let lastChar = key.last
answerFinalDict[Int(lastChar?.description ?? "") ?? 0] = "\(value)"
print("value \(value)")
for (key, value) in answerDict {
print("\(key) -> \(value)")
}
}
Output of print value
:
value 0
value 0
value 1
value 0
value 0
value 1
value 0
value 0
value 1
value 0
value 0
value 0
value 0
value 0
value 1
value 0
value 1
value 1
value 0
value 0
Output of print(answerDict)
["correct_2": 1, "correct_5": 0, "correct_4": 1, "correct_3": 0, "correct_1": 0]
Output of print("\(key) -> \(value)")
correct_2 -> 1
correct_5 -> 0
correct_4 -> 1
correct_3 -> 0
correct_1 -> 0
Please note that print outputs have been shortened for readability.
What I'm trying to achieve is to get the count of occurrences of value
1
I get errors as value of type Any
can't be compared to int
1
,
casting caused crash,
can't use for loop to check for value 1 to do totalCountValOne = 1
Any ideas?
CodePudding user response:
If you want to find the occurrences of value 1 from answerDict
Try this:
If the value is Int
print(answerDict.filter({$0.value as? Int == 1 }).count)
If the value is String
print(answerDict.filter({$0.value as? String == "1" }).count)