gpt4 book ai didi

ios - 在 swift 中使用 JSON 数组

转载 作者:搜寻专家 更新时间:2023-11-01 06:27:12 26 4
gpt4 key购买 nike

我在访问存储在 JSON API 中的信息时遇到问题,只要它位于 [] 括号内而不是 {} 括号内。我正在尝试搜索数组并找到匹配 "job": "director"{} 集。问题是,如果我不使用 CollectionView 等 IndexPath View ,我将无法访问位于 [] 括号内的信息。

JSON:

"crew": [
{
"credit_id": "57ea3a02c3a3687edc00080a",
"department": "Directing",
"gender": 2,
"id": 51329,
"job": "Director",
"name": "Bradley Cooper",
"profile_path": "/z5LUl9bljJnah3S5rtN7rScrmI8.jpg"
},
{
"credit_id": "57ea3a14c3a3687ff9007bd7",
"department": "Writing",
"gender": 2,
"id": 51329,
"job": "Screenplay",
"name": "Bradley Cooper",
"profile_path": "/z5LUl9bljJnah3S5rtN7rScrmI8.jpg"
},
{
"credit_id": "57ea3a27925141108f008807",
"department": "Writing",
"gender": 2,
"id": 224385,
"job": "Screenplay",
"name": "Will Fetters",
"profile_path": null
}
],

这是我的部分代码:

struct Cast: Codable {
let character: String
let name: String
let profile_path: String?
}

struct Crew: Codable {
let name: String
let profile_path: String?
let job: String
}

func loadCredits() {

let id = filmId
let apiKey = ""
let url = URL(string: "https://api.themoviedb.org/3/movie/\(id)/credits?api_key=\(apiKey)")
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: { (dataOrNil, response, error) in
if let data = dataOrNil {
do { let credit = try! JSONDecoder().decode(Credits.self, from: data)
self.filmCast = credit.cast
self.filmCrew = credit.crew


self.castCollection.reloadData()

}
}

self.castCollection.reloadData()

})

task.resume()
}

我可以使用它通过索引路径访问信息:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

let cell = castCollection.dequeueReusableCell(withReuseIdentifier: "castCell", for: indexPath) as! CastCell

let credit = filmCast[indexPath.row]
let name = credit.name

cell.castName.text = name


return cell


}

但如果数据不在 UICollectionView 等 IndexPath View 中,我在搜索数据时遇到问题。

因此,如果我想在 collectionview 之外搜索 job,即 Director,我正在尝试:

if filmCrew.job == "Director" {
perform action here
}

我收到错误:

Value of type '[DetailsView.Crew]' has no member 'job'

所以我的问题是如何正确搜索 JSON 数组以根据匹配值找到数据的匹配 {}。抱歉,如果这个问题听起来很愚蠢或令人困惑,自从使用字典和数组后我就遇到了问题。当我在表和 Collection View 中对其进行索引时,它总是工作正常,但我似乎无法弄清楚如何筛选数组。

最佳答案

您的条件需要遍历整个 filmCrew 数组并找到第一个拥有职位 "Director" 的用户,幸运的是有一种方法可以做到这一点。

if let director = filmCrew.first(where: { $0.job == "Director" }) {
//perform action here
}

关于ios - 在 swift 中使用 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52782485/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com