【问题标题】:How to parse "Rain" from the OpenWeatherMap?如何从 OpenWeatherMap 解析“雨”?
【发布时间】:2018-10-06 21:17:18
【问题描述】:

当从 OpenWeatherMap API 实现 Rain 时,我遇到了这个错误:

'h' 不是整数文字中的有效数字

我有一个单独的 .swift 文档来解析所有 API 引用,并尝试将 Rain 解析为:

struct Rain: Decodable {
let 3h: Double?
}

但我不确定如何解决“Rain: 3h”这样错误不会发生。?

有人可以看看 OpenWeatherMap API 并告诉我他们的想法吗?

更新:

struct.swift:

struct Rain: Decodable {
enum CodingKeys: String, CodingKey { case threeHours = "3h" }

let threeHours: Double?
}

ViewController.swift

@IBOutlet weak var precipitation: UILabel!


let clouding = (self.rain?.threeHours!)!
precipitation.text = precipitation.text! + "  " + String(format:"%.0f", clouding)

【问题讨论】:

标签: swift xcode openweathermap


【解决方案1】:

只需翻译通过 CodingKeys 的密钥

struct Rain: Decodable {
    enum CodingKeys: String, CodingKey { case threeHours = "3h" }

    let threeHours: Double?
}

struct Rain: Codable {
    enum CodingKeys: String, CodingKey { case h3 = "3h" }

    let h3: Double?
}

【讨论】:

  • 或者使用下划线_3h
  • @Carpsen90 因为,正如许多老顽固的 ObjC 开发人员告诉我的那样,_ 倾向于规定“私有”,这可能不是最好的主意,而且,它不完全可读,在哪里与使用 CodingKey 一样,您可以随意命名,使其更具可读性和自我记录性
  • @MadProgrammer 这是真的。 OP 通过使用非法变量名遇到错误。知道名称应该以字母或下划线开头可能会有所帮助。
  • @MadProgrammer 它只是一个名字,和其他名字一样。
  • @Carpsen90 但是在没有CodingKey 的情况下,swift 能否将_3h 映射到3h
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-21
相关资源
最近更新 更多