您好,我正在填充UICollectionView
,但是当执行节数时,它会给我错误
错误
解开值时发现nil
这是我的代码
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
}
}
但是我要崩溃了,所以请帮助我为什么我做错了地方就崩溃了
答案 0 :(得分:3)
在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
}