如何访问数组中自定义对象的值?

时间:2017-02-08 20:46:26

标签: ios arrays swift

我目前有一个自定义对象

public struct GenreData : Decodable {


  public let id : NSNumber?
  public let name : String


  public init?(json: JSON) {

    guard let name : String = "name" <~~ json
      else {return nil}

    self.id = "id" <~~ json
    self.name = name

  }
}

我有一个自定义对象的数组,我正在尝试访问&#39; id&#39;对象的一部分,所以我可以将其插入另一个函数:

  var genreDataArray: [GenreData] = []
  var posterStringArray: [String] = []
  var posterImageArray: [UIImage] = []

 GenreData.updateAllData(urlExtension:"list", completionHandler: { results in

      guard let results = results else {
        print("There was an error retrieving info")
        return
      }
      self.genreDataArray = results

      for _ in self.genreDataArray {

      if let movieGenreID = self.genreDataArray[0].id {//This is where the ID is needed to access the posters

        print(movieGenreID)

        //Update posters based on genreID
        GenrePosters.updateGenrePoster(genreID: movieGenreID, urlExtension: "movies", completionHandler: {posters in

          //Must iterate through multiple arrays with many containing the same poster strings
          for poster in posters {

            //Check to see if array already has the current poster string, if it does continue, if not append to array
            if self.posterStringArray.contains(poster){
              continue
            } else {
              self.posterStringArray.append(poster)

              //Use the poster string to download the corresponding poster
              self.networkManager.downloadImage(imageExtension: "\(poster)",
                { (imageData) //imageData = Image data downloaded from web
                  in
                  if let image = UIImage(data: imageData as Data){
                    self.posterImageArray.append(image)

                  }
              })
            }
          }
        })
      }
      }
      DispatchQueue.main.async {
        self.genresTableView.reloadData()
      }
    })

到目前为止,它所做的一切都是访问JSON数据的第一个数组(有19个数组),并将第一个数组中的每个字符串追加到posterStringArray,但是我需要它来遍历每个数组并只附加如果posterStringArray中已经存在字符串。

1 个答案:

答案 0 :(得分:0)

我不是百分百肯定我理解你的问题,但不应该替换:

for _ in self.genreDataArray {

  if let movieGenreID = self.genreDataArray[0].id 

for item in self.genreDataArray {

  if let movieGenreID = item.id 

<强> 更新

只添加一个项目尝试在获取图像后添加一个中断:

          //Use the poster string to download the corresponding poster
          self.networkManager.downloadImage(imageExtension: "\(poster)",
            { (imageData) //imageData = Image data downloaded from web
              in
              if let image = UIImage(data: imageData as Data){
                self.posterImageArray.append(image)

              }
          })

          break