避免过度!在Swift函数中使用(cellForRowAtIndexPath)

for*_*rin 4 swift

简单地说:我如何避免!在下面的Swift代码中为每一行写作?我考虑过guard,但是UITableViewCell初始化器可以返回nil,但另一方面cellForRowAtIndexPath 必须返回非nil,这本身就是一个矛盾.希望有一个简短而甜蜜的方式.

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!
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*ell 5

??运营商明白,如果RHS不可选的,那么结果是不可选:

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

更好的是,如果您注册单元格标识符(在故事板中或使用registerNib/ registerClass方法),那么您可以使用其中较新的形式dequeueReusableCellWithIdentifier不返回可选项:

let cell = tableView.dequeueReusableCellWithIdentifier("repo", forIndexPath: indexPath)
cell.textLabel?.text = ...  // No ! needed
Run Code Online (Sandbox Code Playgroud)