我希望根据具有最高 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 的电影。我会使用类似于 filter
或 map
的东西吗?
最佳答案
首先在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/