简体   繁体   English

无法将类型“ [String:Any]”的值转换为预期的参数类型“ String”

[英]Cannot convert value of type '[String : Any]' to expected argument type 'String'

I am trying to create a weather App in Swift without using Podfiles and I have reached a stumbling block in terms of passing a dictionary as an argument in parsing JSON. 我试图在不使用Podfiles的情况下在Swift中创建一个Weather App,并且在传递字典作为解析JSON的参数方面,我遇到了绊脚石。 The location function is as follows: 定位功能如下:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location = locations[locations.count - 1]
    if location.horizontalAccuracy > 0 {
        locationManager.startUpdatingLocation()
        locationManager.delegate = nil
        print("longitude = \(location.coordinate.longitude), latitude = \(location.coordinate.latitude)")

        let latitude = String(location.coordinate.latitude)
        let longitude = String(location.coordinate.longitude)
        let params : [String : String] = ["lat" : latitude, "lon" : longitude, "appid" : APP_ID]
        getWeatherData(url: WEATHER_URL, parameters: params)

    }
}

So to parse the JSON I have created the following function: 因此,为了解析JSON,我创建了以下函数:

private func getWeatherData(url: String, parameters: [String : String]) {
    let JsonURLString:[String: Any] = ["url": WEATHER_URL, "parameters": parameters]
    print(JsonURLString)
    guard let url = URL(string: JsonURLString) else { return }
    URLSession.shared.dataTask(with: url) { ( data, response, err ) in
        DispatchQueue.main.sync {
            if let err = err {
                print("Failed to get data from url:", err)
                return
            }
            guard let data = data else { return }
            do {
                let decoder = JSONDecoder()
                decoder.keyDecodingStrategy = .convertFromSnakeCase
                let city = try decoder.decode(WeatherData.self, from: data)
                self.weatherData.city = city.name
            } catch {
                print(error)
                self.cityLabel.text = "Connection issues"
            }
        }
    }.resume()
}

The error I am having is the line Cannot convert the value of type '[String: Any]' to expected argument type 'String' in the line guard let url = URL(string: JsonURLString) else { return } . 我遇到的错误是该行Cannot convert the value of type '[String: Any]' to expected argument type 'String'guard let url = URL(string: JsonURLString) else { return }中的Cannot convert the value of type '[String: Any]' to expected argument type 'String' guard let url = URL(string: JsonURLString) else { return } I am wondering if I have gone down a rabbit hole and maybe use an alternative approach. 我想知道我是否掉进了兔子洞,也许使用了另一种方法。 I wanted to use codable in Swift 4 as this is supposed to be an easier way of parsing JSON. 我想在Swift 4中使用codable,因为这应该是解析JSON的更简单方法。 Now in this example, I am not sure. 现在在这个例子中,我不确定。 Any help would be much appreciated. 任何帮助将非常感激。

Try this code. 试试这个代码。

JsonURLString is a [String: Any] type object not a String type. JsonURLString是[String:Any]类型的对象,而不是String类型。 So you nee to convert it to a String type object. 因此,您需要将其转换为String类型的对象。

private func getWeatherData(url: String, parameters: [String : String]) {
   let JsonURLString:[String: Any] = ["url": WEATHER_URL, "parameters": parameters]
   print(JsonURLString)
   let urlString = JsonURLString["url"] as? String
   guard let url = URL(string: urlString!) else { return }
   URLSession.shared.dataTask(with: url) { ( data, response, err ) in
   DispatchQueue.main.sync {
      if let err = err {
          print("Failed to get data from url:", err)
          return
      }
      guard let data = data else { return }
       do {
           let decoder = JSONDecoder()
           decoder.keyDecodingStrategy = .convertFromSnakeCase
           let city = try decoder.decode(WeatherData.self, from: data)
           self.weatherData.city = city.name
         } catch {
           print(error)
           self.cityLabel.text = "Connection issues"
         }
      }
   }.resume()
}

暂无
暂无

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

相关问题 无法转换类型[[String:Any]? 到预期的参数类型“ _?” - Cannot convert value of type '[String:Any]?' to expected argument type '_?' 无法将类型“x”的值转换为预期的参数类型“[String: Any]” - Cannot convert value of type 'x' to expected argument type '[String : Any]' 无法将“String”类型的值转换为预期的参数类型“[Any]” - Cannot convert value of type 'String' to expected argument type '[Any]' 无法将类型'String?.Type'的值转换为预期的参数类型'String?' - Cannot convert value of type 'String?.Type' to expected argument type 'String?' 无法将类型(“字符串:字符串”)的值转换为预期的参数类型“ URL” - Cannot convert value of type ('string: String)' to expected argument type 'URL' 无法将类型“ [String:Any]”的值转换为预期的参数类型“ [NSAttributedStringKey:Any]” - Cannot convert value of type '[String : Any]' to expected argument type '[NSAttributedStringKey : Any]' 无法转换'NSString'类型的值? 预期参数类型'String' - Cannot convert value of type 'NSString'? to expected argument type 'String' 无法将“字符串”类型的值转换为预期的参数类型“ NSManagedObject” Swift - Cannot convert value of type 'String' to expected argument type 'NSManagedObject' Swift 无法将类型“()”的值转换为预期的参数类型“字符串” - Cannot convert value of type '()' to expected argument type 'String' 无法转换'String?'类型的值 预期的参数类型'URL' - Cannot convert value of type 'String?' to expected argument type 'URL'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM