将JSON结果与字符串比较
我试图从一个url得到一个JSON结果,并检查它是否等于“OK”,这样我就可以预制一个segue。我目前收到错误: Binary operator '==' cannot be applied to operands of type 'Any' and 'String'
。将JSON结果与字符串比较
这里是我的代码:
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()
谢谢!
P.S.做print(response)
就好了。
编译器必须知道(预期)类型的response
if let jsonData = try JSONSerialization.jsonObject(with: content) as? [String:Any] {
if let response = jsonData["response"] as? String { ...
一如往常:
- 不要使用
NSDictionary
斯威夫特 - 切勿斯威夫特使用
.mutableContainers
,这是毫无意义的。
好的,现在测试一下:) –
这个工作,但是当我尝试执行一个segue时,它告诉我把'performSegue(withIdentifier:“loginSegue”,sender:response)''改为'self.performSegue withIdentifier:“loginSegue”,sender:response)',这样做会在运行时崩溃应用程序。我怎样才能解决这个问题? –
是否存在具有标识符'loginSegue'的segue?什么错误信息得到? – vadian
首先不要使用NSDictionary,使用本地Swift结构数组。 如果您想通过'if if response = responseData [“response”]将其与字符串进行比较,您还需要对String进行响应? String'。 –