1

Swift beginner is here. I am reading a textbook of Swift and found a strange expression... what is this code (second "let" line) doing? Please take a look at the thing between equal sign and the UITableVIewCell method. To me it looks like "c is not nil, it should be optional, and c should be unwrapped...."

(c != nil) ? c!

It is hard for me to search it in the internet (google) because I cannot make a good search keywords in the search engine for the question.

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
}
uPlayer
  • 13
  • 3

2 Answers2

3

The line

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

is demonstrating the ? ternary operator.

If c != nil then c! is returned, else the call is made to UITableViewCell.

The code could be simplified to use the shorthand nil coalescing operator:

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

Similar question/answer here.

Community
  • 1
  • 1
1

It's a ternary operator. Normally a bit hard to wrap your head around to begin with. It works like this:

If the (c != nil) is true (i.e. c exists) then cell == c! (from the left side of the :). On the other hand, if c is nil then (c != nil) returns false, then cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "table_cell") from the right side of the colon.

You might want to play around with this in the playground to get a better understanding of how it works:

let text = "foo" // try changing this to something else entirely
let output = text == "foo" ? text : "bar"
print(output)
T. Benjamin Larsen
  • 6,373
  • 4
  • 22
  • 32