【问题标题】:Trying to get a String out of an Array (Open Weather Map)尝试从数组中获取字符串(打开天气图)
【发布时间】:2015-09-13 10:58:46
【问题描述】:

我正在尝试使用 swift 从Open Weather Map API (json) 获取天气数据。我设法使用这个来访问温度

if let main = json["main"] as? NSDictionary {
    println(main)
    if var temp = main["temp"] as? Double {
        temperatureLabel.text = String(format: "%.1fº K", temp)
    }
}

很遗憾,我无法访问天气描述!我试过了

if let weather = json["weather"] as? NSArray {
    println(weather)
    if var temp = weather["description"] as? String {
        descriptionLabel.text = weatherDescription
    }
}

我只是不知道该尝试什么,因为我是 Swift 新手,以前从未使用过 json。

【问题讨论】:

  • 请显示您正在执行的请求以及您是如何执行的。
  • weather 是字典数组吗?如果是这样,您需要先为数组下标。试试weather[0]["description"] as? String
  • 您也可以尝试在String 之前将第一个向下转换为AnyObject,例如:weather["description"] as AnyObject! as? String
  • 由 vacawama 解决,谢谢!

标签: json swift ios8 nsarray nsdictionary


【解决方案1】:

weather 是字典的array,因此array 需要下标如下:

if let weather = json["weather"] as? NSArray {
    println(weather)
    if var temp = weather[0]["description"] as? String {
        descriptionLabel.text = weatherDescription
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-06
    • 2019-05-28
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    • 2018-04-24
    • 2022-12-18
    • 2019-03-06
    相关资源
    最近更新 更多