TomSawyer
TomSawyer

Reputation: 3820

XCode 6 beta 7 error with swift

Previous version is beta 6 , my project worked fine. I just updated my xcode to version 6 beta 7 and getting error , really don't know how to fix it.

var currentcell = collectionView.cellForItemAtIndexPath(indexPath)
var posx = currentcell.frame.origin.x-collectionView.contentOffset.x

Error report: 'UICollectionViewCell?' does not have a member named 'frame' Xcode 6 beta 7 suggest me add ? after current cell. i changed it to

var posx = currentcell?.frame.origin.x-collectionView.contentOffset.x

But still error: Error report: Value of optional type 'CGFloat?' not unwrapped; did you mean to use '!' or '?'? Anyone can help?

Upvotes: 2

Views: 557

Answers (3)

Jean Lebrument
Jean Lebrument

Reputation: 5169

try this:

if currentcell != nil
{
    var posx = currentcell!.frame.origin.x-collectionView.contentOffset.x
}

Upvotes: 0

Mike Pollard
Mike Pollard

Reputation: 10195

To avoid runtime crashes when no cell is returned for the given indexPath do:

if let currentcell = collectionView.cellForItemAtIndexPath(indexPath) {
    var posX = currentcell.frame.origin.x - collectionView.contentOffset.x
    // .. do something
}
else {
    // ... there was no cell so do something else
}

Upvotes: 1

Sulthan
Sulthan

Reputation: 130072

This is correct. Using ? in

currentcell?.frame.origin.x makes the whole expression an optional (CGFloat?). You cannot do arithmetic operations on optionals. You have to unwrap the value first.

What do you expect posX to be when currentCell is nil?

Probably what you want to do is to force unwrapping the cell value:

var posX = currentcell!.frame.origin.x - collectionView.contentOffset.x

In older betas most of the obj-c types were explicitely unwrapped optionals (UITableViewCell!) but some of them were made into pure optionals (UITableViewCell?). Note that there are cases when the currentCell is nil. You should handle these cases.

Upvotes: 3

Related Questions