简体   繁体   English

无法分配“ NSDictionary”类型的值? 键入“字符串?”

[英]Cannot assign value of type 'NSDictionary?' to type 'String?'

Below is my code (Swift 4.2.1) for getting response from API.But while calling it showing some error as, 下面是我从API获取响应的代码(Swift 4.2.1),但是在调用时显示了一些错误,

Cannot assign value of type 'NSDictionary?' 无法分配“ NSDictionary”类型的值? to type 'String?' 键入“字符串?”

let task = URLSession.shared.dataTask(with: request) { data, response, error in
   guard let data = data, error == nil else {
      return
   }
   let responseString = String(data: data, encoding: .utf8)
   print("responseString = \(String(describing: responseString))")
   do {
    let jsonResponse = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary
     print(jsonResponse!)
     responsevalue = jsonResponse

     let alert1 = UIAlertController(title: "Alert", message: self.responsevalue, preferredStyle: UIAlertController.Style.alert)
     let action1 = UIAlertAction(title: "Ok",style: .default)
     {(ACTION)in
     }
     alert1.addAction(action1)
     self.present(alert1, animated: true, completion: nil)
     }catch let parsingError {
        print("Error", parsingError)

        let alert1 = UIAlertController(title: "Alert", message: parsingError as? String, preferredStyle: UIAlertController.Style.alert)
        let action1 = UIAlertAction(title: "Ok",style: .default)
         {(ACTION)in
         }
         alert1.addAction(action1)
         self.present(alert1, animated: true, completion: nil)
         }
       }
      task.resume()

Don't use NSDictionary . 不要使用NSDictionary Use [String: Any] . 使用[String: Any] You need to get the message string from the dictionary to show in the alert. 您需要从字典中获取消息字符串以显示在警报中。

let jsonResponse = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
print(jsonResponse)
responsevalue = jsonResponse
guard let message = jsonResponse["msg"] as? String else {//Use the key from json
    return
}
let alert1 = UIAlertController(title: "Alert", message: message, preferredStyle: .alert)

In else part instead of using parsingError, use parsingError.localizedDescription 在其他部分,请使用parsingError.localizedDescription而不是parsingError

let alert1 = UIAlertController(title: "Alert", message: parsingError.localizedDescription, preferredStyle: .alert)

as the error says Cannot assign value of type 'NSDictionary?' to type 'String?' 如错误所示, Cannot assign value of type 'NSDictionary?' to type 'String?' Cannot assign value of type 'NSDictionary?' to type 'String?' . You are assigning NSDictionary to a variable who's type is String. 您正在将NSDictionary分配给类型为String的变量。

You need to change the original declaration of responseString to NSDictionary or your another variable to store your NSDictionary. 您需要将responseString的原始声明更改为NSDictionary或另一个变量以存储NSDictionary。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM