Avoid excessive! use in Swift function (cellForRowAtIndexPath)

Simply put: How can I avoid writing !for each line in the Swift code below? I thought guard, but the UITableViewCell initializer can return zero, but on the other hand it cellForRowAtIndexPathshould return non-nil, which seems to be a contradiction. Hope there is a short and sweet way.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier)
    if cell == nil {
        cell = UITableViewCell(style: .Default, reuseIdentifier: reuseIdentifier)
    }
    cell!.textLabel?.text = ...
    cell!.textLabel?.textColor = ...
    cell!.detailTextLabel?.textColor = ...
    cell!.detailTextLabel?.textColor = ...
    return cell!
}
+4
source share
3 answers

The operator ??understands that if rhs is not optional, then the result is not optional:

let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier)
    ?? UITableViewCell(style: .Default, reuseIdentifier: reuseIdentifier)
cell.textLabel?.text = ...  // No ! needed

, ( , registerNib/registerClass), dequeueReusableCellWithIdentifier, :

let cell = tableView.dequeueReusableCellWithIdentifier("repo", forIndexPath: indexPath)
cell.textLabel?.text = ...  // No ! needed
+5

API UITableView:

    public func dequeueReusableCellWithIdentifier(identifier: String, forIndexPath indexPath: NSIndexPath) -> UITableViewCell 
// newer dequeue method guarantees a cell is returned and resized properly, assuming identifier is registered

, , , .

+2

You can also make the code as follows:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier)! 
    cell.textLabel?.text = ...
    cell.textLabel?.textColor = ...
    cell.detailTextLabel?.textColor = ...
    cell.detailTextLabel?.textColor = ...
    return cell
}
-1
source

All Articles