ios - 根据 Int 查找 JSON 字典中的前 10 项

标签 ios arrays json swift

我希望根据具有最高 Int 的 JSON 字典提取前 10 个实例。

因此,对于我展示的示例,我要根据受欢迎程度排名寻找排名前 10 位的电影。我在下面发布了字典的示例。

部分词典:

{
"cast": [
{
  "id": 201,
  "character": "Praetor Shinzon",
  "original_title": "Star Trek: Nemesis",
  "overview": "En route to the honeymoon of William Riker to Deanna Troi on her home planet of Betazed, Captain Jean-Luc Picard and the crew of the U.S.S. Enterprise receives word from Starfleet that a coup has resulted in the installation of a new Romulan political leader, Shinzon, who claims to seek peace with the human-backed United Federation of Planets. Once in enemy territory, the captain and his crew make a startling discovery: Shinzon is human, a slave from the Romulan sister planet of Remus, and has a secret, shocking relationship to Picard himself.",
  "vote_count": 643,
  "video": false,
  "media_type": "movie",
  "release_date": "2002-12-13",
  "vote_average": 6.2,
  "title": "Star Trek: Nemesis",
  "popularity": 7.61,
  "original_language": "en",
  "genre_ids": [
    28,
    12,
    878,
    53
  ],
  "backdrop_path": "/1SLR0LqYPU3ahXyPK9RZISjI3B7.jpg",
  "adult": false,
  "poster_path": "/n4TpLWPi062AofIq4kwmaPNBSvA.jpg",
  "credit_id": "52fe4226c3a36847f8007d05"
},
{
  "id": 855,
  "character": "Spec. Lance Twombly",
  "original_title": "Black Hawk Down",
  "overview": "When U.S. Rangers and an elite Delta Force team attempt to kidnap two underlings of a Somali warlord, their Black Hawk helicopters are shot down, and the Americans suffer heavy casualties, facing intense fighting from the militia on the ground.",
  "vote_count": 2540,
  "video": false,
  "media_type": "movie",
  "release_date": "2001-12-28",
  "vote_average": 7.3,
  "title": "Black Hawk Down",
  "popularity": 11.504,
  "original_language": "en",
  "genre_ids": [
    28,
    36,
    10752
  ],
  "backdrop_path": "/7u2p0VxnhVMHzfSnxiwz5iD3EP7.jpg",
  "adult": false,
  "poster_path": "/yUzQ4r3q1Dy0bUAkMvUIwf0rPpR.jpg",
  "credit_id": "52fe4282c3a36847f80248ef"
},

从这本字典中,根据受欢迎程度排名得出前 10 名电影的正确代码是什么?

部分代码如下:

 struct Cast: Codable {
    let title: String
    let character: String
    let poster_path: String?
    let id: Int
    let popularity: Double?
}

var filmCredits = [Cast]()

我遇到的第一个问题是当我使用 return 10 返回 10 个结果时:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 10
}

在我的 cellForItemAt 函数中调用 indexPath 时,我收到错误 Thread 1: Fatal error: Index out of range

这是 JSON 解码器函数:

func loadFilms() {

    let apiKey = ""
    let url = URL(string: "https://api.themoviedb.org/3/person/\(id)/combined_credits?api_key=\(apiKey)&language=en-US")
    let request = URLRequest(
        url: url! as URL,
        cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalCacheData,
        timeoutInterval: 10 )

    let session = URLSession (
        configuration: URLSessionConfiguration.default,
        delegate: nil,
        delegateQueue: OperationQueue.main
    )

    let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
        if let data = data {
            do {
                let films = try! JSONDecoder().decode(Credits.self, from: data)
                self.filmCredits = films.cast!
                self.topCollection.reloadData()

            }

        }

        self.topCollection.reloadData()

    })


    task.resume()

}

我最不确定的是如何只提取排名前 10 的电影。我会使用类似于 filtermap 的东西吗?

最佳答案

首先在Credits中声明cast是非可选的

struct Credits: Decodable {
    let cast: [Cast]
}

分配给数据源数组时,按流行度降序排列

self.filmCredits = films.cast.sorted{($0.popularity ?? 0.0) > $1.popularity ?? 0.0})

不要硬编码 numberOfItemsInSection。如果 cast 数组包含的项目少于 10 个,则会发生崩溃。添加条件,如果项目数大于 10,则显示 10 项,否则为数组中的项目数。

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    let numberOfCredits = filmCredits.count
    return numberOfCredits > 10 ? 10 : numberOfCredits
}

并且捕获可能的错误并在主线程上重新加载 Collection View

if let data = data {
    do {
        let films = try JSONDecoder().decode(Credits.self, from: data)
        self.filmCredits = films.cast.sorted{($0.popularity ?? 0.0) > $1.popularity ?? 0.0})
    } catch{ print(error) }
}
DispatchQueue.main.async {
    self.topCollection.reloadData()
}

关于ios - 根据 Int 查找 JSON 字典中的前 10 项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52907334/

相关文章:

java - 从类到 B 类调用数组

java - 从 Jersey 1.* 升级到 Jersey 2.5

ios - Crashlytics 2.1.9 升级阻止应用程序启动

ios - 使用 UITextView 自动调整 UITableViewCell 的大小,其中文本同时与垂直中心对齐?

ios - UITextField 委托(delegate) "shouldChangeCharactersIn"未调用文本字段中的第一个条目

java - 是否可以让 Gson 跳过类型错误的字段?

php - 有没有办法将多个数组传递给 PHP json_encode 并用 jQuery 解析它?

iphone - 通知问题

java - 将矩阵(二维数组)旋转 X.XX°

java - 如何在 Java 中移动数组中的位置?