Objective-C – 如何获得Boleans的总和?

通过下面的代码,我可以得到一个输出,如:
0
1
1

我想要的是输出这些布尔值的总和,在我的情况下,结果将是:
2因为我们有0+1+1

代码[更新]:

  -(void)markers{ CLLocationCoordinate2D tg = CLLocationCoordinate2DMake(location.latitude, location.longitude); GMSCoordinateBounds *test = [[GMSCoordinateBounds alloc]initWithPath:path]; BOOL test3 = [test containsCoordinate:tg]; { if (test3 == 1) { marker.position = CLLocationCoordinate2DMake(location.latitude, location.longitude); }else if (test3 == 0) { marker.position = CLLocationCoordinate2DMake(0, 0); } } } } 

而不是总结布尔,这是违反直觉,循环不pipe你用什么来获得布尔值,如果你得到是,增加一个计数器。 这将是你有的是的数量。

如果你有一个BOOL数组,你可以用一个谓词来过滤数组,得到YES值,结果数组的长度就是你拥有的YES数。

在OP注释之后编辑添加代码示例

增加一个计数器

 NSUInteger numberOfBools = 0; CLLocationCoordinate2D tg = CLLocationCoordinate2DMake(location.latitude, location.longitude); GMSCoordinateBounds *test = [[GMSCoordinateBounds alloc]initWithPath:path]; if ([test containsCoordinate:tg1]) { ++numberOfBools; } if ([test containsCoordinate:tg2]) { ++numberOfBools: } ... // other tests here; // numberOfBools now contains the number of passing tests. 

在完整的代码被添加后再次编辑

 // snipped code above here // This is where you add the counter and initialise it to 0 NSUInteger numberOfBools = 0; for (NSDictionary *dictionary in array) { // Snip more code to this point BOOL test3 = [test containsCoordinate:tg]; { if (test3) { // This is where you increment the counter ++numberOfBools; // Snip more code to the end of the for block } // Now numberOfBools shows how many things passed test3 
 int sum = (test3 ? 1 : 0) + (testX ? 1 : 0) + (testY ? 1 : 0); 

而不是那么奇怪的变体:

 #define BOOL_TO_INT(val) ((val) ? 1 : 0) int sum = BOOL_TO_INT(test3) + BOOL_TO_INT(testX) + BOOL_TO_INT(testY); 

可以添加BOOLs,因为bools只是整数。 例如:

 int sum = 0; CLLocationCoordinate2D tg = CLLocationCoordinate2DMake(location.latitude, location.longitude); GMSCoordinateBounds *test = [[GMSCoordinateBounds alloc]initWithPath:path]; BOOL test3 = [test containsCoordinate:tg]; //Obtain bolean values : BOOL testX = /* other test */; BOOL testY = /* other test */; sum = test3 + testX + testY 

然而,这是一个坏主意,因为BOOL不一定是10 。 他们是0not 0

BOOL只是一个typedef-ed char: typedef signed char BOOL; YESNO是1和0,但是BOOL variable = 2是完全有效的

例如:

 - (int) testX { if(inState1) return 1; if(inState2) return 2; else return 0; } BOOL textXResult = [self testX]; //Might return 2, this is still equivalent to YES. 

最好的解决scheme是迭代你的BOOL,而是计算YESes的数量。

另一种方法是假定如果任何一个值为假,那么整个数组就是假的,因此,循环数组直到find一个假值,然后break:

 BOOL retval = true; //return holder variable /*'boolsNumArray' is an NSArray of NSNumber instances, converted from BOOLs: //BOOL-to-NSNumber conversion (makes 'boolsNumArray' NSArray, below)! '[myNSArray addObject:[NSNumber numberWithBool:yourNextBOOL]]' */ for(NSNumber* nextNum in boolsNumArray) { if([nextNum boolValue] == false) { retval = false; break; } } return retval;