首页 文章

匹配SwiftyJson中的确切键

提问于
浏览
-1

我确实在确定SwiftyJson中返回的特定值时遇到了麻烦;希望有人可以帮我向我解释一下 .

我想看看预定的单词“apple”与从JSON响应中收到的任何单词之间是否匹配 .

如果匹配则显示消息,并且用户选择进入下一级别或用户返回主屏幕 .

如果没有匹配则显示消息,并且用户必须继续播放或取消播放 .

我想在不同级别的游戏中为多个单词执行此操作 .

第一级:将“apple”与任何收到的JSON响应匹配 .

第二级:将“计算机”与任何收到的JSON响应相匹配 .

第三级:将“电话”或“电话”或“iPhone”或“Android”或任何或所有上述内容与任何收到的JSON响应相匹配 .

所以,基本上,我可以获得所有JSON响应,但是我很难找到如何设置以确定是否返回了特定的预定义JSON响应 .

我已经看了几个星期与另一个帖子,但无济于事:(

JSON RESPONSES

{
  "responses" : [
    {
      "labelAnnotations" : [
        {
          "mid" : "\/m\/01m2v",
          "score" : 0.9245476,
          "description" : "computer keyboard"
        },
        {
          "mid" : "\/m\/01c648",
          "score" : 0.7945268,
          "description" : "laptop"
        },
        {
          "mid" : "\/m\/01mfj",
          "score" : 0.74227184,
          "description" : "computer hardware"
        },
        {
          "mid" : "\/m\/0541p",
          "score" : 0.7062791,
          "description" : "multimedia"
        },
        {
          "mid" : "\/m\/07c1v",
          "score" : 0.7039645,
          "description" : "technology"
        },
        {
          "mid" : "\/m\/03gq5hm",
          "score" : 0.69323385,
          "description" : "font"
        },
        {
          "mid" : "\/m\/0bs7_0t",
          "score" : 0.6724673,
          "description" : "electronic device"
        },
        {
          "mid" : "\/m\/01vdm0",
          "score" : 0.66489816,
          "description" : "electronic keyboard"
        },
        {
          "mid" : "\/m\/0121tl",
          "score" : 0.60392517,
          "description" : "electronic instrument"
        },
        {
          "mid" : "\/m\/0h8n5_7",
          "score" : 0.5834592,
          "description" : "laptop replacement keyboard"
        }
      ]
    }
  ]
}

CODE TO SHOW ALL JSON RESPONSES

// Use SwiftyJSON to parse results
        let json = JSON(data: dataToParse)
        let errorObj: JSON = json["error"]

 // Parse the response
            print(json)
            let responses: JSON = json["responses"][0]

                // Get label annotations
            let labelAnnotations: JSON = responses["labelAnnotations"]
            let numLabels: Int = labelAnnotations.count
            var labels: Array<String> = []
            if numLabels > 0 {
                var labelResultsText:String = "Labels found: "
                for index in 0..<numLabels {
                    let label = labelAnnotations[index]["description"].stringValue
                    labels.append(label)
                }
                for label in labels {
                    // if it's not the last item add a comma
                    if labels[labels.count - 1] != label {
                        labelResultsText += "\(label), "
                    } else {
                        labelResultsText += "\(label)"
                    }
                }
                self.labelResults.text = labelResultsText
            } else {
                self.labelResults.text = "No labels found"
            }

EDIT

我显然无法回答我自己的问题,我会发布一个编辑,因为我认为这是一个更好的解决方案,但@ pierce对于一个单词来说相当不错,而不是很多;它只是不适用于游戏设置应用程序 .

所以,我创建了一个新的NSObject,创建了一个

static var _words: [[String]] = [

["apple", computer", "beer"]]

然后

func checkAnnotations(annotations: [Annotation]) -> Bool {
    var isMatched = false

    let searchWords = self.words
    for searchWord in searchWords {
        for annotation in annotations {
            if searchWord == annotation.descriptionString {
                isMatched = true
                break
            }
        }

        if isMatched {
            break
        }
    }

    return isMatched
}

然后创建了一个处理水平状态的函数,

最后将其与View Controller中的JSON响应进行比较,如果匹配则与高级级别进行比较

// Get JSON key value
            let labelAnnotations = responses["labelAnnotations"].arrayValue
            let annotationObjects: [Annotation] = labelAnnotations.flatMap({ annotationDictionary in
                if let mid = annotationDictionary["mid"].string,
                let score = annotationDictionary["score"].double,
                    let description = annotationDictionary["description"].string {
                    let annotation = Annotation(mid: mid, score: score, descriptionString: description)
                    return annotation
                }

                return nil
            })

            //print(annotationObjects)

            let searchString = LevelState.shared.words[0]
            print("Level \(LevelState.shared.level), looking for: \(searchString)")

            var isMatched = LevelState.shared.checkAnnotations(annotations: annotationObjects)
            if isMatched {
                LevelState.shared.advance()
            }

            let alertTitle = isMatched ? "Congrats! You got \(searchString)" : "Keep looking for \(searchString)"

            //let translationResult = "Translated: \(levelDescription) to \(translatedText)"

            let alertController = UIAlertController(title: alertTitle, message: nil, preferredStyle: .alert)
            alertController.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
            self.present(alertController, animated: true, completion: nil)

            }

        self.prepareForNewLevel()
        })
    }

1 回答

  • 0

    第一件事 - 我真的没有必要 . 你是否对分离数组中的元素感到困惑?因为只有当你手动写出数组的元素(即 let array = ["a", "b", "c"] )时,才会实际使用 String .

    那么就说你为这个 labels 数组设置了一个属性,这是一个 String 的数组 .

    var labels: Array<String> = []
    

    一旦你完成并附加了 JSON 的所有 description 值,你就可以操纵它了 .

    if numLabels > 0 {
    
        for index in 0..<numLabels {
            let label = labelAnnotations[index]["description"].stringValue
            labels.append(label)
        }
    
    }
    

    现在,您可以创建一个方法,该方法将根据用户输入的单词返回 String 的过滤数组:

    func findMatches(_ userEntry: String) -> [String] {
    
        return labels.filter { $0.contains(userEntry) }
    
    }
    

    现在你可以使用上面的方法来处理某种类型的用户输入,比如说你有一个名为 textFieldUITextField 文本:

    // Return the filtered matches based on the textField text (unless nil)
    let matches = findMatches(textField.text ?? "")
    
    // Print the number of matches, and also show the matches
    print("Found \(matches.count) matches to user input\r\(matches)")
    

    现在如果你有 labels 持有 ["a", "aa", "ba", "b", "c", "apple"] ,并运行上面的代码,其中 userEntry 只是字母"a",你会在控制台窗口中看到这个打印出来:

    Found 4 matches to user input
    ["a", "aa", "ba", "apple"]
    

    编辑 - 你可以使用上面的 findMatches 方法来确定你所做的事情,但是有几种不同的方法 . 首先,假设您有一组预先确定的单词要检查为数组:

    let words = ["word", "verb", "noun", "adverb"]
    

    然后你可以遍历它并检查每一个

    for word in words {
    
        let matches = findMatches(word)
        if matches.count > 0 {
            print("Found \(matches.count) matches to \(word)\r\(matches)")
        } else {
            // Do whatever you want when there are no matches
            print("No matches found")
        }
    
    }
    

    如果您只想检查特定单词并获得特定响应,可以设置如下方法:

    func checkWord(word: String, noMatchResponse: String) {
    
        let matches = findMatches(word)
        if matches.count > 0 {
            print("Found \(matches.count) matches to \(word)\r\(matches)")
        } else {
            // Do whatever with the no match response
            print(noMatchResponse)
        }
    
    }
    

    有很多方法可以实现这一点 . 您还可以使用 switch 语句,然后对每个预定义词使用不同的 case 语句 . 这完全取决于您以及您希望如何设计游戏 .

相关问题