您好,我正在填充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中的主题数,如果subjectsnil,则返回0

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return subjects?.subjectList.count ?? 0
}

现在subjectList内部的每个主题都具有subList数组属性。在numberOfItemsInSection中,返回某些subListsubjectList中的元素数(现在,您可以强制解开subjects,因为您知道numberOfSections大于0的情况)
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return subjects!.subjectList[section].subList.count
}

10-08 02:00