查找基于 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
}

我在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()
}

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

首先在非可选Credits声明cast

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

分配给数据源数组时按popularity降序对数组进行排序

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
}

catch可能的错误并在主线程上重新加载集合视图

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()
}

你需要

filmCredits.sort{ $0.popularity > $1.popularity}

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

不能在委托方法中写入return 10collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int。您不能确定您总是会得到 10 个结果。如果少于 10 个,则应用会在itemForRowAt中崩溃。

注意:你提到了cellForRowAt这是UITableView的,但你的代码显示collectionView,确保你使用的是正确的委托方法。

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

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

最新更新