首先,我将使用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 摆脱了条件可选绑定的塔,但我仍然发现缺乏一种优雅的方式来处理可选的而不用大括号。