ios - 匹配 SwiftyJson 中的精确键

标签 ios json swift swifty-json

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

我想查看预定单词“apple”与从 JSON 响应接收到的任何单词之间是否存在匹配。

如果匹配,则会显示一条消息,用户可以选择进入下一个级别或返回主屏幕。

如果没有匹配,则会显示一条消息,用户必须继续玩或取消玩。

我想对游戏不同级别的多个单词执行此操作。

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

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

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

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

我已经到处找了好几个星期的另一篇文章,但没有结果:(

JSON 响应

    {
  "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"
        }
      ]
    }
  ]
}

显示所有 JSON 响应的代码

 // 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"
            }

编辑

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

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

静态变量_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()
        })
    }

最佳答案

首先 - 我真的不明白为什么你想在每个描述的末尾添加一个逗号。我真的认为这是没有必要的。您对分隔数组中的元素感到困惑吗?因为实际的 String 不需要这样做,所以只有当您手动写出数组的元素时(即 let array = ["a", "b", "c"])。

那么假设您为此 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)")

现在,如果您有标签,其中包含["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 语句。这完全取决于您以及您想要如何设计游戏。

关于ios - 匹配 SwiftyJson 中的精确键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42353010/

相关文章:

ios - 如何正确设置导航栏中图像的约束?

iphone - BOOL 本身在 ViewController 之间从 YES 变为 NO?

ios - 我在 iOS 应用程序中使用 MBtiles 作为离线 map ,如何将更新的 MB tiles 与旧的合并。我用的是mac系统

ios - 重用dispatch_get_main_queue()/dispatch_get_global_queue()的结果是否安全?

c# - 如何将 .NET Core API 配置为始终返回 JSON

java - 如何从 Android 读取 MYSQL 数据库?

ios - 将标题添加到 TableViewController

Swift Float 到 UInt8 的转换没有必要吗?

javascript - 使用存储在数组中的数据动态构建 JSON

ios - 协议(protocol)委托(delegate)在自定义 UIView 按钮中不起作用