uPlayer uPlayer - 5 months ago 12
Swift Question

Assignment in bracket in Swift

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
}

Answer

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.

Comments