【问题标题】:For loop in JSON data using swift使用 swift 在 JSON 数据中循环
【发布时间】:2016-06-05 16:47:46
【问题描述】:

我正在解析 JSON 数据并遍历结果,一切都很好。但我需要一种方法来控制循环内的迭代次数。例如只获取前 10 个结果。

这里我正在解析 JSON 天气数据状态图标。我只想获取前 10 个结果并将它们附加到数组中。

if let list = arrayList["weather"] as? [[String : AnyObject]]{

  for arrayList in list{

     if let iconString = arrayList["icon"] as? String{
        if let url = NSURL(string: "http://openweathermap.org/img/w/\(iconString).png"){
           let iconImgData = NSData(contentsOfURL: url)
           let image = UIImage(data: iconImgData!)
           self.forcastImg.append(image!)                                                                  self.forcastView.reloadData()

                    }
              }
         //print(list)
     }
  }

【问题讨论】:

  • 你的意思是arrayList[0..<10]
  • @Cristik 是的,但我只需要正确的语法。或者,嘿,也许我可以添加一个 var i=0 ,当它达到

标签: arrays json xcode swift loops


【解决方案1】:

这是一个非常快速的解决方案:

let first10Images = (arrayList["weather"] as? [[String : AnyObject]])?.reduce((0, [UIImage]())) {
    guard $0.0.0 < 10,
        let iconString = $0.1["icon"] as? String,
        url = NSURL(string: "http://openweathermap.org/img/w/\(iconString).png"),
        iconImgData = NSData(contentsOfURL: url),
        image = UIImage(data: iconImgData)
        else {
            return $0.0
    }
    return ($0.0.0 + 1, $0.0.1 + [image])
}.1

基本上,您通过使用由计数器和结果数组组成的对来减少 weather 数组。如果计数器超过 10,或者您无法下载图像,您只需通过返回累积值移动到下一项,否则您增加计数器并附加下载的图像。

请注意,您会得到一个可选的,因为第一次转换可能会失败。但是我相信你不会有这个问题,从发布的代码中考虑到你知道如何处理选项:)

【讨论】:

    【解决方案2】:

    有很多方法可以做到这一点。

    按照您的建议,您可以手动控制循环运行前 n 个元素:

    if let list = arrayList["weather"] as? [[String : AnyObject]] {
    
       for i in 0 ..< 10 {
          let arrayList = list[i]
          // Do stuff with arrayList
       }
    }
    

    如果您知道数组的长度至少为 10,则可以使用 Cristik 在他的评论中建议的 ArraySlice syntax

    if let list = arrayList["weather"] as? [[String : AnyObject]] where list.count > 10 {
       let firstTenResults = list[0 ..< 10]
       for arrayList in firstTenResults {
          // Do stuff with arrayList
       }
    }
    

    不过,prefix(_:) 方法可能是最清晰的。此方法的优点是,如果您提供的参数大于数组的长度,它将返回您拥有的元素而不会引发错误:

    if let list = arrayList["weather"] as? [[String : AnyObject]] {
       let firstTenResults = list.prefix(10)
       for arrayList in firstTenResults {
          // Do stuff with arrayList
       }
    }
    

    【讨论】:

    • 感谢@Ronald Martin,它成功了。我用list.prefixUpTo(Int)
    猜你喜欢
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 2016-11-27
    • 2018-04-21
    • 2016-12-06
    • 2018-07-04
    • 1970-01-01
    相关资源
    最近更新 更多