您好,我正在填充UICollectionView
,但是执行节数时却给我以下错误:
错误
展开价值时发现零
这是我的代码
var subjects: SubjectResponse?
func callSubChapAPI(){
let preferences = UserDefaults.standard
let studentlvl = "student_lvl"
let student_lvl = preferences.object(forKey: studentlvl) as! String
print(student_lvl)
let params = ["level_id": student_lvl]
Alamofire.request(subListWithChapter, method: .post, parameters: params).responseData() { (response) in
switch response.result {
case .success(let data):
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
self.subjects = try decoder.decode(SubjectResponse.self, from: data)
self.collView.reloadData()
} catch {
print(error.localizedDescription)
}
case .failure(let error):
print(error.localizedDescription)
}
}
}
}
extension ExploreTableViewCell : UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return self.subjects!.subjectList.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.subjects!.subjectList.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ExploreCollectionViewCell
let url = subjects!.subjectList[indexPath.section].subList[indexPath.row].chImage
print(url)
return cell
}
}
但是我要崩溃了,所以请帮助我为什么我做错了地方就崩溃了
最佳答案
在numberOfSections
中,您需要返回subjectList
中的主题数,如果subjects
是nil
,则返回0
func numberOfSections(in collectionView: UICollectionView) -> Int {
return subjects?.subjectList.count ?? 0
}
现在
subjectList
内部的每个主题都具有subList
数组属性。在numberOfItemsInSection
中,返回某些subList
的subjectList
中的元素数(现在,您可以强制解开subjects
,因为您知道numberOfSections
大于0的情况)func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return subjects!.subjectList[section].subList.count
}