0

I'm trying to build a collection view with pagination (showing cells as previews) and found this tutorial. I'm getting the error from Xcode and guessing this must be due to an update to Xcode (since the tutorial seemed to have worked for a lot of people). Would love a hint on how to fix this:

Downcast from '[UICollectionViewLayoutAttributes]?' to '[UICollectionViewLayoutAttributes]' only unwraps optionals; did you mean to use '!'?

rantanplan
  • 243
  • 3
  • 17

1 Answers1

0

You probably did something like this (someOptionalAttributes being of type [UICollectionViewLayoutAttributes]?):

someOptionalAttributes as! [UICollectionViewLayoutAttributes]

However, because someOptionalAttributes is just the optional version of [UICollectionViewLayoutAttributes], you do not need a force downcast, you just need to unwrap it:

someOptionalAttributes!

Force downcasting is only necessary if casting to an entirely new type (usually subclass).

So, yes, you did mean to use ! as said in the error. If you want to be safe, you could use a number of different optional unwrapping techniques.

tktsubota
  • 9,371
  • 3
  • 32
  • 40
  • Thanks! I tried modifying the line into "if let attributesForVisibleCells = self.layoutAttributesForElementsInRect(cvBounds)!" but then I get this error: Initializer for conditional binding must have Optional type, not '[UICollectionViewLayoutAttributes]' – rantanplan Mar 16 '16 at 02:14
  • @moopoints Ah, because when you use `if let`, you don't need force downcasting. Just change it to `if let attributesForVisibleCells = self.layoutAttributesForElementsInRect(cvBounds)` — without the `!`. – tktsubota Mar 16 '16 at 02:23
  • Done! Thanks again – rantanplan Mar 16 '16 at 03:49