Please explain this weird way of setting up a cellular accessory.

I saw the following line of code here , while Googling to answer another mine question .

cell.accessoryType = (UITableViewCellAccessoryNone + UITableViewCellAccessoryCheckmark) - cell.accessoryType; 

It seems that code is running from this thread. I'm just wondering, is this code superfluous? If you know accessoryType , why subtract it from this expression?

+4
source share
2 answers

If the membership attribute was UITableViewCellAccessoryNone, then the expression network will set it to UITableViewCellAccessoryCheckmark.

If the membership attribute was UITableViewCellAccessoryCheckmark, then the expression network will set it to UITableViewCellAccessoryNone.

It's just a shortcut saying

 if (cell.accessoryType == UITableViewCellAccessoryNone) cell.accessoryType = UITableViewCellAccessoryCheckmark else if (cell.accessoryType == UITableViewCellAccessoryCheckmark) cell.accessoryType = UITableViewCellAccessoryNone 

Definitely an example of running code ... I would not have avoided this.

+4
source

Given that this code switches between UITableViewCellAccessoryCheckmark and UITableViewCellAccessoryNone and tries to be concise, another alternative that I find clearer would be:

 cell.accessoryType ^= UITableViewCellAccessoryCheckmark|UITableViewCellAccessoryNone; 

This statement is clearer in its intent and eliminates the need for a conditional statement - which may or may not be useful depending on how often it is called.

+1
source

All Articles