Swift中括号中的赋值

时间:2016-06-20 05:41:06

标签: ios swift

Swift初学者来了。 我正在读一本关于Swift的教科书,发现了一个奇怪的表达......这段代码(第二个“让”行)是做什么的?请看一下等号和UITableVIewCell方法之间的事情。 对我来说,它看起来像“c不是零,它应该是可选的,而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
}

2 个答案:

答案 0 :(得分:2)

该行

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

答案 1 :(得分:1)

这是一个ternary operator。通常有点难以开始。它的工作原理如下:

如果(c!= nil)为真(即c存在),则cell == c!(来自:)的左侧。另一方面,如果c 为nil,则(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)