Avoid Index Out Of Range error in swift

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Avoid Index Out Of Range error in swift



In my UICollectionView I'm trying to return 1 item, if there's no data (in order to set an empty cell then).
Here is the code:


var movies = [Movies]()


func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
if movies.count == 0
return 1
else
return movies.count




I'm getting Fatal Error: Index Out Of Range. I know, that this way I'm trying to access an element under index[1] and that's impossible, because that element doesn't exist, that's the reason of this error.



But how can I avoid it in this case?





In this function you are saying... If I have no items... tell the collection view that I have 1 item. If you just return movies.count here your problem will go away. Also... your crash is not here... it is somewhere else.
– Fogmeister
Aug 10 at 11:36



movies.count




1 Answer
1



As of you are returning 1 count in numberOfItemsInSection for empty array you need to check that your array is empty or not in cellForItemAt before subscripting with it.


1


numberOfItemsInSection


cellForItemAt


func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
if movies.isEmpty
//return your empty cell

else
//access array element and return cell






Oh, I was declaring my 2 cells and then in return I was like: return movies.count == 0 ? emptyCell : cell I wonder why this doesn't work, but anyway.. Your case worked Thanks a lot!
– Emma Vagradyan
Aug 10 at 11:44






@EmmaVagradyan Welcome mate :)
– Nirav D
Aug 10 at 11:45





@EmmaVagradyan just wondering, if you're using return movies.count == 0 ? emptyCell : cell then it should also work.
– Kamaldeep singh Bhatia
Aug 10 at 11:45


return movies.count == 0 ? emptyCell : cell





@NiravD, a big thanks, you really saved my day!
– Emma Vagradyan
Aug 10 at 11:50





oh, Yes... Thanks @NiravD
– Kamaldeep singh Bhatia
Aug 10 at 13:10






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard