Objective-C - How to get sum of Boleans?

后端 未结 4 1209
迷失自我
迷失自我 2021-01-29 06:58

Through the code below, I can get an output such as :
0
1
1

What I want is to output the sum of these boolea

4条回答
  •  执笔经年
    2021-01-29 07:12

    Rather than sum BOOLs, which is counterintuitive, loop over whatever you are using to get the BOOL values, and if you get YES, increment a counter. This will be the number of YESs that you have.

    If you have an array of BOOLs, you could just filter the array with a predicate to get the YES values and the length of the resulting array is the number of YESs that you have.

    Edited to add code samples following OP comments

    Incrementing a counter

    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.
    

    Edited Again, after the full code was added

    // 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
    

提交回复
热议问题