静态tableview中的数组中的复杂json数据数组(详细信息)

时间:2018-07-18 16:54:17

标签: arrays swift

import UIKit

struct Base : Codable {
    let genres : [Genres]?
    let name : String?
    let overview : String?
}

struct Genres : Codable {
    let id : Int?
    let name : String?
}

func fillSelectedShowDetails() {
    let selectedURL = URL(string: " ")

    guard let downloadedURL = selectedURL else {return}
    URLSession.shared.dataTask(with: downloadedURL) { (data, urlResponse, error) in
        guard let data = data, error == nil, urlResponse != nil else {
            print("something went wrong in selectedURL")
            return
        }
        print("Downloaded selectedURL")
        do {
            let decoder = JSONDecoder()
            let decodedResults = try decoder.decode(Base.self, from: data)
            self.detailedTV = decodedResults

            DispatchQueue.main.async {
                self.showNameLabel.text = decodedResults.name
                self.overwievLabel.text = decodedResults.overview
                if self.detailedTV?.genres?.count == 2 {
                    self.genreLabel.text = decodedResults.genres?[1].name
                } else {
                    self.genreLabel.text = decodedResults.genres?[0].name
                }

                print(decodedResults.genres)
            }
        } catch {
            print("something wrong after downloaded in selectedURL\(error)")
        }
    }.resume()
}

我需要每个流派名称并将其写到文本中。我该怎么办?

1 个答案:

答案 0 :(得分:0)

如果您的目标是从name属性的所有值中创建一个字符串,请使用mapjoined

let genreNames = decodedResults.genres?.compactMap { $0.name }.joined(separator: ",") ?? """
self.genreLabel.text = genreNames