Reputation: 320
I have an array that I am filling with boolean values in the following code.
for(int i = 0; i < 15; i++){
int checkVal = [(NSNumber *)[__diceValue objectAtIndex:i] intValue];
if(checkVal == matchVal){
[_diceMatch replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:y]];
}
}
Whats the shortest way to write a conditional to check the array "_diceMatch" for all true values?
Upvotes: 1
Views: 100
Reputation: 46578
Shortest way? maybe not. Easiest way? Yes
- (BOOL)isDictMatchAllTrue {
for (NSNumber *n in _dictMatch) {
if (![n boolValue]) return NO;
}
return YES;
}
or you don't like writing loop
NSSet *set = [NSSet setWithArray:_diceMatch];
return set.count == 1 && [[set anyObject] boolValue];
Note: first version return YES
when array is empty but second version return NO
.
You can add
if (_dictMatch.count == 0) return YES; //or NO
to fix it.
Upvotes: -1
Reputation: 539685
If your array can only contain the values "true" (@YES
) or "false" (@NO
)
then you can simply check for the absence of @NO
:
if (![_diceMatch containsObject:@NO]) {
// all elements are "true"
}
Upvotes: 2
Reputation: 1101
NSUInteger numberOfTrueValues = 0;
for (NSNumber *value in _diceMatch) {
if ([value boolValue]) {
numberOfTrueValues++;
}
}
Upvotes: 0