草庐IT

Swift 样式 : Function returns optional of type that you need in order to continue, 处理此问题的最佳做法是什么?

coder 2023-09-10 原文

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

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

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

最佳答案

在这种情况下你可以这样写

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 实例。

关于Swift 样式 : Function returns optional of type that you need in order to continue, 处理此问题的最佳做法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35527786/

有关Swift 样式 : Function returns optional of type that you need in order to continue, 处理此问题的最佳做法是什么?的更多相关文章

随机推荐