首页 > 解决方案 > 根据 Int 查找 JSON 字典中的前 10 个项目

问题描述

我正在寻找基于具有最高 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
}

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

这是 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 的电影。我会使用类似于filteror的东西map吗?

标签: iosarraysjsonswift

解决方案


你不能写return 10在委托方法collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int中。你不能确定你总是有 10 个结果。如果少于 10 个,您的应用程序会在itemForRowAt.

注意:您提到cellForRowAt哪个是 for UITableViews 但您的代码显示collectionView,请确保您使用的是正确的委托方法。

然后填写一个包含流行度信息的数组,按降序对其进行排序,然后你就可以使用像Sh_Khan提到的东西了:

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

推荐阅读