简体   繁体   中英

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,

Cannot assign value of type '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 . Use [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

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?' . You are assigning NSDictionary to a variable who's type is String.

You need to change the original declaration of responseString to NSDictionary or your another variable to store your NSDictionary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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