Le Toucan Sale Le Toucan Sale - 1 year ago 326
Swift Question

collectionView: reloadData works, reloadItemsAtIndexPaths does not (Swift)

I have a

whose source data changes sometimes when offscreen. To update it when it returns, I wrote in the

override func viewWillAppear(animated: Bool) {

...and that works, but I never need to update more than one or two cells in my
, so I thought it'd be better if I replaced the above version with:

override func viewWillAppear(animated: Bool) {

...but when I do, Xcode gives me an error saying:

Operand of postfix '!' should have optional type, delete '!'".

When I delete the '!', it says that
doesn't have a member named
. What am I doing wrong?

Thanks for the help!

Answer Source

From your code it looks like you have declared your collectionView as Optional (with ?) at the end and maybe linked it to your storyboard using an @IBOutlet. To fix your issue you should remove the ? from the :

@IBOutlet var collectionView: UICollectionView?

and substitute it with:

@IBOutlet var collectionView: UICollectionView!

this way you are telling the compiler that your collectionView definitely exists (because you have linked it from your storyboard).

Alternatively, you can bind your collectionView by doing this:

if let collectionView = collectionView {