I'm looking over the diffs submitted to a project by another developer, and they have a lot of code that does !!<some BOOL value>
. In fact, this seems to be their standard pattern for implementing boolean getters and setters. Th开发者_C百科ey've implemented their code like:
- (BOOL) hasId {
return !!hasId_;
}
- (void) setHasId:(BOOL) value {
hasId_ = !!value;
}
I've never seen this pattern before, and am wondering if there is any benefit in using it. Is the double-negation doing anything useful?
The double boolean operator just makes sure that the value returned is either a 1 or a 0. That's all : )
!
is a logical negation operator. So if setHasId: was passed, eg., 0x2 then the double negation would store 0x1.
It is equivalent to:
hasId_ = value ? 1 : 0;
It is useful in some cases because if you do this:
BOOL x = y & MY_FLAG;
You might get 0 if MY_FLAG
is set, because the result gets truncated to the size of a BOOL
(8 bits). This is unexpected. For the same reasons, people sometimes prefer that BOOL
is either 0 or 1 (so bit operations work as expected). It is usually unnecessary.
In languages with a built-in bool
type such as C (as of C99) and C++, converting an integer to bool
does this automatically.
It makes more sense in some other cases for example where you are returning BOOL
but don't want to put an if
statement in.
- (BOOL)isMyVarSet
{
return !!myVar;
}
In this case I can't just return myVar
because it's not a BOOL
(this is a very contrived example - I can't dig out a decent one from my projects).
I've used this before and I believe:
if (!!myVar)
is equivalent to:
if (myVar != nil)
Basically, I use it to verify the value of SOMETHING.
I will admit... this is probably not the best practice or most-understood way to accomplish this goal.
精彩评论