展开UITableViewCell的Optionals

时间:2015-10-23 02:08:33

标签: ios swift2 optional

我有以下代码。我正在使用所有可能的Xcode建议以及SO等各种来源,但我似乎无法纠正可选问题:

var cell =
        tableview!.dequeueReusableCellWithIdentifier(identifier as String) as? UITableViewCell?

        if (cell == nil)
        {
            cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier:identifier as String)
            cell.backgroundColor = UIColor.clearColor()
// ERROR HERE 
        }

        cell.textLabel?.text = dataArray.objectAtIndex(indexPath.row).valueForKey("category_name") as! String
        // ERROR HERE

        var str = String(format: "%@%@%@",kServerURl,"/upload/",dataArray.objectAtIndex(indexPath.row).valueForKey("category_image") as! String)

        cell?.imageView?.image =  UIImage(data: NSData(contentsOfURL: NSURL(string:str)!)!)
// ERROR HERE

        return cell
//ERROR HERE

错误:

  

可选类型UITABLEVIEWCELL的价值没有取消,你的意思是使用!还是?

如果我使用,无所谓!要么 ?我得到同样的错误,在某些情况下错误将解决,如果两个!添加了tier cell !!。

2 个答案:

答案 0 :(得分:4)

问题是你在这里有双重选项:

var cell =
    tableview!.dequeueReusableCellWithIdentifier(identifier as String) as? UITableViewCell?

as?表示演员表可能会失败,因此它会包含您在可选内容中投射的值。您正在投放的价值是可选的(String?)。因此,如果您在调试器中查看单元格的值,您会看到如下内容:

Optional(Optional(<UITableViewCell:0x14f60bb10

您可以通过执行以下操作显式解包:

cell!!(两个惊呼),但这有点脏。相反,你只需要其中一个演员:

var cell =
    tableview!.dequeueReusableCellWithIdentifier(identifier as String) as? UITableViewCell

注意我删除了最后一个问号。然后你可以这样做:

cell!.backgroundColor = UIColor.clearColor()

最后一个选择就是用一个感叹号强行打开它:

tableview!.dequeueReusableCellWithIdentifier(identifier as String) as! UITableViewCell

那么你需要的只是:

cell.backgroundColor = UIColor.clearColor()

答案 1 :(得分:1)

单元格变量是UITableViewCell类型的可选项,因此您必须在使用它之前将其解包。您应该阅读the documentation on Optional Types以熟悉它们的使用。像这样的行:

cell.backgroundColor = UIColor.clearColor()

应该是:

cell!.backgroundColor = UIColor.clearColor()

或:

if let someCell = cell {
    someCell.backgroundColor = UIColor.clearColor()
}

在您知道实例不是nil的情况下,您将使用第一种解包方式,就像直接在nil检查if语句之后一样。如果你不确定它不是nil,你会使用第二种展开。

相关问题