Swift 3 - 将用户输入与字典值匹配

时间:2017-03-02 03:54:30

标签: swift

我的应用程序的用户将使用他们的英语进行测试。他们将通过在单词旁边放置一个复选标记从列表中选择不同的单词。他们只想选择名词。例如,如果他们正确地选择了10分中的5分,我如何向他们显示50%的分数。我认为我需要根据用户的输入过滤字典值。用户的输入是一个数组。编码的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

请尝试以下代码: - 100%正常工作

     let myDictionary : [String : Any] =
        [  "Nouns":["One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten"],
"Verbs":["Eat","play","dance","walk","run","sing","read","write","go","come"]]
    var myUserSelectedArray:[String] = ["One","come","Three","go","Five","x","Six","x","x","Ten"];

    let myNounArray = myDictionary["Nouns"] as? [String];
    let myVerbArray = myDictionary["Verbs"] as? [String];
    let set1:Set<String> = Set(myUserSelectedArray);
    let set2:Set<String> = Set(myNounArray!);
    let set3:Set<String> = Set(myVerbArray!);
    let scroeInNoun = set1.intersection(set2).count;
    let scroeInVerb = set1.intersection(set3).count;
    print ("score in Verb \((scroeInVerb * 100)/set2.count) %")
    print ("score in noun \((scroeInNoun * 10)/set3.count ) %")
    let finalScore = (scroeInNoun + scroeInVerb) * 100 / ((myNounArray?.count)! + (myVerbArray?.count)!)
    print ("final score in noun \(finalScore) %") 

如果对您有用,请接受答案