将JSON结果与String进行比较

问题描述 投票:-3回答:1

我正在尝试从URL获取JSON结果并检查它是否等于“OK”,因此我可以预先形成segue。我目前正在收到错误:Binary operator '==' cannot be applied to operands of type 'Any' and 'String'

这是我的代码:

        let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error != nil {
            print("LightningDB Error")
        } else {
            if let content = data {
                do {
                    let jsonData = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject

                    if let responseData = jsonData as? NSDictionary {
                        if let response = responseData["response"] {
                            if response == "OK" {
                                performSegue(withIdentifier: "loginSegue", sender: responseString)
                            } else {
                                warnField.text = "This user does not exist."
                            }
                        }
                    }

                } catch {

                }
            }
        }
    }

    task.resume()

谢谢!

附:做print(response)就好了。

json swift
1个回答
1
投票

编译器必须知道(预期)类型的response

if let jsonData = try JSONSerialization.jsonObject(with: content) as? [String:Any] {
    if let response = jsonData["response"] as? String { ...

一如既往:

  • 不要在Swift中使用NSDictionary
  • 永远不要在Swift中使用.mutableContainers,这是没有意义的。
© www.soinside.com 2019 - 2024. All rights reserved.