Is there a way to put a condition that return true only if one of the two component return true?
BOOL var1
BOOL var2
something shorter than if((var1 && !var2) || (!var1 && var2))
Thank you
Is there a way to put a condition that return true only if one of the two component return true?
BOOL var1
BOOL var2
something shorter than if((var1 && !var2) || (!var1 && var2))
Thank you
As Objective-C is a superset of C, you simply use the XOR operator from C, which is ^
.
XOR
if(!!var1 != !!var2)
{
NSLog(@"XOR condition");
}
Exclamation marks convert vars to BOOL (real conversion, not casting)
So this solution works even if your variables are not BOOL.
!!(0|nil) ≡ 0
!!(any other number|object) ≡ 1
This is useful in cases when you want to be sure that only one of vars is nonnil.
You could add more clearness to the code that Ishu suggests by doing this:
#define XOR !=
and then you just write:
if (var1 XOR var2) {
...
}
truth table output:
[T XOR T => F; T != T => F],
[T XOR F => T; T != F => T],
[F XOR T => T; F != T => T] and
[F XOR F => F; F != F => F]
A macro could be an option. It will keep the same behaviour, but now in a more readable way.
#define XOR(x,y) (((x) && !(y)) || (!(x) && (y)))
if(XOR(var1, var2) {
}