我正在解析json数据并迭代结果,一切都很好。但我需要一种方法来控制循环中的迭代次数。例如只得到前10个结果。
这里是im解析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)
     }
  }

最佳答案

有很多方法可以做到这一点。
如您所建议的,您可以手动控制循环以运行前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
   }
}

10-01 23:52
查看更多