简体   繁体   English

类型“”不符合协议“可编码”

[英]Type ' ' does not conform to protocol 'Encodable'

Can someone tell what's wrong here please?有人可以告诉这里有什么问题吗?

It send me this error: Type 'CityWeatherInfo' does not conform to protocol 'Encodable'它向我发送此错误:类型“CityWeatherInfo”不符合协议“Encodable”


struct CityWeatherInfo: Codable {
   var name: String
   var main: Main
   var weathers: [Weather]

   private enum CodingKeys: String, CodingKey {
       case weathers = "weather"
       case main = "main"
       case name

   }
   init(from decoder: Decoder) throws {
       let container = try decoder.container(keyedBy: CodingKeys.self)
       self.name = try container.decode(String.self, forKey: .name)
       let mainContainer = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .main)
       let weatherContainer = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .weathers)
   }
}

struct Weather: Decodable {
   var main: String
   var description: String

   private enum WeatherKeys: String, CodingKey {
       case main = "main"
       case description = "description"
   }
}

struct Main: Decodable {
   var temp: Double
   var feels_like: Double
   var temp_min: Double
   var temp_max: Double

   private enum MainKeys: String, CodingKey {
       case temp = "temp"
       case feels_like = "feels_like"
       case temp_min = "temp_min"
       case temo_max = "temp_max"
   }
}

Json is this: Json 是这样的:

{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04n"}],"base":"stations","main":{"temp":287.45,"feels_like":286.61,"temp_min":284.82,"temp_max":289.15,"pressure":1012,"humidity":72},"visibility":10000,"wind":{"speed":1,"deg":0},"clouds":{"all":100},"dt":1592362322,"sys":{"type":1,"id":1414,"country":"GB","sunrise":1592365362,"sunset":1592425222},"timezone":3600,"id":2643743,"name":"London","cod":200} {"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":804,"main":"Clouds","description":"阴云"," icon":"04n"}],"base":"stations","main":{"temp":287.45,"feels_like":286.61,"temp_min":284.82,"temp_max":289.15,"pressure": 1012,"湿度":72},"能见度":10000,"风":{"速度":1,"度":0},"云":{"全部":100},"dt":1592362322 ,"sys":{"type":1,"id":1414,"country":"GB","sunrise":1592365362,"sunset":1592425222},"timezone":3600,"id":2643743 ,"名称":"伦敦","鳕鱼":200}

If a struct or class adopts Codable the required methods init(from decoder: Decoder) and encode(to encoder: Encoder) are synthesized by default.如果结构或 class 采用Codable ,则默认情况下会合成所需的方法init(from decoder: Decoder)encode(to encoder: Encoder)

But if you implement one of the methods yourself you have to implement the other, too.但是,如果您自己实现其中一种方法,那么您也必须实现另一种方法。 Or – in this case – adopt only Decodable because you are only reading/decoding the data.或者——在这种情况下——只采用Decodable因为你只是在读取/解码数据。

There are a few bad practices in your code.您的代码中有一些不好的做法。

  • The custom CodingKeys WeatherKeys and MainKeys are pointless because in the default syntax the framework generates the keys named CodingKeys .自定义 CodingKeys WeatherKeysMainKeys没有意义,因为在默认语法中,框架会生成名为CodingKeys的键。 Custom keys are considered only in a custom implementation.自定义键仅在自定义实现中被考虑。

  • Both nestedContainers are not needed and they make no sense anyway if they are keyed by the same CodingKeys.两个nestedContainers都不需要,如果它们由相同的 CodingKeys 键控,它们无论如何都没有意义。

  • You can omit the CodingKeys if the dictionary keys match the struct member names.如果字典键与结构成员名称匹配,则可以省略 CodingKeys。

  • If the values of the struct members are not going to be modified declare them as constants ( let ).如果不修改结构成员的值,请将它们声明为常量( let )。

  • According to the naming convention variables are supposed to be named lowerCamelCased .根据命名约定,变量应该被命名为lowerCamelCased A convenient way to translate snake_case to camelCase is to specify the convertFromSnakeCase key decoding strategy.snake_case转换为camelCase的一种便捷方法是指定convertFromSnakeCase密钥解码策略。


The openweathermap API provides degrees in Celsius by adding units=metric in the URL or Fahrenheit by adding units=imperial . openweathermap API 通过在 URL 中添加units=metric来提供摄氏度或通过添加units=imperial来提供华氏度。 For example例如

https://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid=•••••••••••••"

The UNIX timestamps (1592362322) can be decoded as Date by specifying the secondsSince1970 date decoding strategy UNIX 时间戳(1592362322)可以通过指定secondsSince1970日期解码策略解码为Date

The structs can be created in this simple form可以以这种简单的形式创建结构

struct CityWeatherInfo: Decodable {
   let name: String
   let main: Main
   let weather: [Weather]
   let dt : Date
}

struct Weather: Decodable {
   let main: String
   let description: String
}

struct Main: Decodable {
   let temp, tempMin, tempMax, feelsLike : Double
}

And decode the data with this code并使用此代码解码数据

 do {
     let decoder = JSONDecoder()
     decoder.keyDecodingStrategy = .convertFromSnakeCase
     decoder.dateDecodingStrategy = .secondsSince1970
     let weatherInfo = try decoder.decode(CityWeatherInfo.self, from: data)
     print(weatherInfo)
 } catch {
    print(error)
 }

暂无
暂无

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

相关问题 类型“ AreaData”不符合协议“可编码” - Type 'AreaData' does not conform to protocol 'Encodable' 如果我在 swift 的结构中使用协议类型,我的结构不符合协议“可解码”/“可编码” - My structure does not conform to protocol 'Decodable' / 'Encodable' if I use protocol type in my structure in swift swift 将字典转换为 jsonString 错误:协议类型 'Any' 不能符合 'Encodable' 因为只有具体类型才能符合协议 - swift Convert dictionary to jsonString error : Protocol type 'Any' cannot conform to 'Encodable' because only concrete types can conform to protocols SwiftUI-类型“服务”不符合协议“可解码” - SwiftUI - Type 'Service' does not conform to protocol 'Decodable' Argo:类型不符合“可解码”协议 - Argo: Type does not conform to protocol 'Decodable' 类型[String:String]不符合协议“ AnyObject” - type [String: String] does not conform to protocol 'AnyObject' Swift 4.2:类型“ T”不符合协议“可解码” - Swift 4.2 : Type 'T' does not conform to protocol 'Decodable' Swift,ObjectMapper:类型“用户”不符合协议“可映射” - Swift, ObjectMapper: Type 'User' does not conform to protocol 'Mappable' 类型“字符串”不符合协议“ NSCopying”-数组swift json错误 - Type 'String' does not conform to protocol 'NSCopying' - Array swift json Error 如何在Swift 4可编码协议中使用JSON字典类型编码属性 - How to encode a property with type of JSON dictionary in Swift 4 encodable protocol
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM