3

首先,我将使用cellForRowAtIndexPath它作为我的示例,因为 de-queue 函数返回一个可选项并忽略显式解包它是完全安全的事实。

我的问题是:什么被认为是“最佳”方式或风格来处理您调用返回可选的函数但您需要从此函数返回以继续操作的情况。我发现第一个片段非常笨拙和丑陋:

if let theCell = UITableView().dequeueReusableCellWithIdentifier("cell") {
    setUpCell(theCell)
    return theCell
  } else {
    let theCell = UITableViewCell(style: .Default, reuseIdentifier: "cell")
    setUpCell(theCell)
    return theCell
}

另一种选择是:

let getNewCell = { return UITableViewCell(style: .Default, reuseIdentifier: "cell") }
let cell = UITableView().dequeueReusableCellWithIdentifier("cell") ?? getNewCell()
setUpCell(cell)
return cell

我们用 Swift 2 摆脱了条件可选绑定的塔,但我仍然发现缺乏一种优雅的方式来处理可选的而不用大括号。

4

1 回答 1

2

在这种情况下,你可以写

var theCell = tableView.dequeueReusableCellWithIdentifier("cell")
if theCell == nil { theCell = UITableViewCell(style: .Default, reuseIdentifier: "cell") }
setUpCell(theCell)
return theCell

但是,在这种情况下,返回非可选的方法更可取

let theCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
setUpCell(theCell)
return theCell

并使用传递的UITableView实例。

于 2016-02-20T19:21:28.110 回答