【问题标题】:Cannot assign value of type 'NSDictionary?' to type 'String?'无法分配“NSDictionary”类型的值?键入“字符串?”
【发布时间】:2019-05-20 11:16:13
【问题描述】:

下面是我从 API 获取响应的代码 (Swift 4.2.1)。但是在调用它时显示一些错误,

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

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()

【问题讨论】:

  • responsevalue = jsonResponse,这里我收到错误,无法分配“NSDictionary”类型的值?输入“字符串?”
  • 你在哪一行得到了错误信息
  • JSON 响应:responseString = Optional("{\"status\":\"500\",\"msg\":\"用户名或密码不正确\"}") { msg = "用户名或密码错误”;状态 = 500; }

标签: ios arrays json swift


【解决方案1】:

不要使用NSDictionary。使用[String: Any]。您需要从字典中获取消息字符串以显示在警报中。

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)

在 else 部分,不要使用 parsingError,而是使用 parsingError.localizedDescription

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

【讨论】:

    【解决方案2】:

    正如错误所说Cannot assign value of type 'NSDictionary?' to type 'String?'。您将 NSDictionary 分配给类型为 String 的变量。

    您需要将 responseString 的原始声明更改为 NSDictionary 或您的另一个变量来存储您的 NSDictionary。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-11
      相关资源
      最近更新 更多