【问题标题】:Assignment in bracket in SwiftSwift中括号中的赋值
【发布时间】:2016-10-21 06:43:59
【问题描述】:

Swift 初学者来了。 我正在阅读 Swift 的教科书,发现一个奇怪的表达......这段代码(第二个“let”行)在做什么?请看一下等号和 UITableVIewCell 方法之间的关系。 对我来说,它看起来像“c 不是 nil,它应该是可选的,并且 c 应该被解包......”

(c != nil) ? c!

我很难在互联网(谷歌)中搜索它,因为我无法在搜索引擎中为该问题做出好的搜索关键字。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    //create cells in table
    let c = tableView.dequeueReusableCellWithIdentifier("table_cell")
    let cell = (c != nil) ? c!: UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "table_cell")
return cell
}

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    线

    let cell = (c != nil) ? c!: UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "table_cell")
    

    正在演示 ? ternary operator.

    如果c != nil 则返回c!,否则调用UITableViewCell

    代码可以简化为使用简写的 nil 合并运算符:

    let cell = c ?? UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "table_cell")
    

    类似的问题/答案here

    【讨论】:

      【解决方案2】:

      这是一个ternary operator。通常一开始有点难以绕开你的头。它的工作原理是这样的:

      如果 (c != nil) 为真(即 c 存在),则 cell == c!(从 : 的左侧开始)。另一方面,如果 c is nil then (c != nil) 返回 false,则从冒号右侧算起 cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "table_cell")

      您可能想在操场上玩弄它以更好地了解它的工作原理:

      let text = "foo" // try changing this to something else entirely
      let output = text == "foo" ? text : "bar"
      print(output)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-19
        相关资源
        最近更新 更多