Vishal Parmar
Vishal Parmar

Reputation: 612

Getting crash while execute numberof sections in collection view

Hello I am populating an UICollectionView but when executing number of section its give me error that

Error

Found nil while unwrapping value

here is my Code

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
    } 
}

But I am getting crash so please help me why i am getting crash where I am done wrong

Upvotes: 1

Views: 334

Answers (1)

Robert Dresler
Robert Dresler

Reputation: 11200

In numberOfSections you need to return number of subjects in subjectList, if subjects is nil, return 0

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

now every subject inside subjectList has property which is array subList. In numberOfItemsInSection return number of elements in subList for certain subjectList (now you can force-unwrap subjects because you know that there is any if numberOfSections is more then 0)

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return subjects!.subjectList[section].subList.count
}

Upvotes: 3

Related Questions