Sydney Loteria Sydney Loteria - 7 months ago 14
Swift Question

Return cell outside if-else

i encounter a problem when I return the cell outside the if-else it gives me an error of "Use of unresolved identifer 'cell'". Here's my code:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

if let feedItem = feeds.objectAtIndex(UInt(indexPath.row)) as? FeedsDataModel {
if feedItem.media_url != "" {
let cell = tableView.dequeueReusableCellWithIdentifier("FeedsTableWithImgCell", forIndexPath: indexPath) as! FeedsTableViewWithImageCell
cell.setupCellWithFeedItem()
}
else {
let cell = tableView.dequeueReusableCellWithIdentifier("FeedsTableWithoutImgCell", forIndexPath: indexPath) as! FeedsTableViewWithoutImageCell
cell.setupCellWithFeedItem()
}

return cell
}
}

Answer

use like

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

if let feedItem = feeds.objectAtIndex(UInt(indexPath.row)) as? FeedsDataModel {
    if feedItem.media_url != "" {
        let cell = tableView.dequeueReusableCellWithIdentifier("FeedsTableWithImgCell", forIndexPath: indexPath) as! FeedsTableViewWithImageCell
        cell.setupCellWithFeedItem()
        return cell
    }
    else {
        let cell = tableView.dequeueReusableCellWithIdentifier("FeedsTableWithoutImgCell", forIndexPath: indexPath) as! FeedsTableViewWithoutImageCell
        cell.setupCellWithFeedItem()
        return cell
    }


}
}

Update

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

  let cell: FeedsTableViewWithImageCell

if let feedItem = feeds.objectAtIndex(UInt(indexPath.row)) as? FeedsDataModel {
    if feedItem.media_url != "" {
         cell = tableView.dequeueReusableCellWithIdentifier("FeedsTableWithImgCell", forIndexPath: indexPath) as! FeedsTableViewWithImageCell
        cell.setupCellWithFeedItem()

    }
    else {
         cell = tableView.dequeueReusableCellWithIdentifier("FeedsTableWithoutImgCell", forIndexPath: indexPath) as! FeedsTableViewWithoutImageCell
        cell.setupCellWithFeedItem()

    }


}
     return cell
}

Edit & update

   func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

if let feedItem = feeds.objectAtIndex(UInt(indexPath.row)) as? FeedsDataModel {
    var cell:FeedsTableViewWithImageCell!
    if feedItem.media_url != "" {
        cell = tableView.dequeueReusableCellWithIdentifier("FeedsTableWithImgCell", forIndexPath: indexPath) as! FeedsTableViewWithImageCell
        cell.setupCellWithFeedItem()
    }
    else {
       let cell1 = tableView.dequeueReusableCellWithIdentifier("FeedsTableWithoutImgCell", forIndexPath: indexPath) as! FeedsTableViewWithoutImageCell
        cell1.setupCellWithFeedItem()
         return cell1
    }

    return cell
}
}
Comments