1290 1290 - 3 months ago 23
Swift Question

Unexpected Non Void return value in CollectionView cellForItemAtIndexPath Datasource method

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as? PictureCellForHomeVC {
picArray[indexPath.row].getDataInBackgroundWithBlock({ (data: NSData?, error: NSError?) in
if error == nil {
if let data = data {
let image = UIImage(data: data)
cell.imageView.image = image
return cell
}
}
})
}else {
return UICollectionViewCell()
}
}


In the above code I receive the error:

Unexpected Non Void return value in void function


The
picArray
in my above code is code with
PFFile
objects which I can call the
getDataInBackgroundWithBlock
method.

I understand what the error means since the completionHandler of the
getDataInBackgroundWithBlock
returns
void
so I can't return my cell in it, but I am stuck on how to fix this problem.

I can't even pass a seperate closure to the method
cellForItemAtIndexPath
since I do not call the method and it is a datasource method. Does anyone know how I can fix this issue?

Answer

You're trying to return something that you think is returning within your function but is actually trying to return something from getDataInBackgroundWithBlock which is supposed to return void (which is not allowed hence the error).

You could do something like this which loads the image in the background while giving it a placeholder image in the meantime (for added effect):

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as? PictureCellForHomeVC {
        picArray[indexPath.row].getDataInBackgroundWithBlock({ (data: NSData?, error: NSError?) in
            if error == nil {
                self.loadImage(inImageView: cell.imageView, withData: data)
            }
        })
        return cell 
    } else {
        return UICollectionViewCell()
    }
} else {
    return UICollectionViewCell()
}


func loadImage(inImageView imageView: PFImageView, withData imageFile: PFFile?) {
    imageView.image = UIImage(named: "placeholder.png") // Some placeholder while the image loads asyncronously
    if let imageFile = imageFile {
        imageView.file = imageFile
        imageView.loadInBackground(nil)
    }
}
Comments