Search code examples
iosarraysswiftfor-in-loop

Looping through arrays and increasing counters in Swift


So I am trying to loop through an array and increase a two counters based on the index in the array. The array has boolean values in it and the counters are for said boolean values. My implementation is error filled, so I am trying to figure out whether my logic is incorrect or my implementation is incorrect. So an extra pair of eyes would help

var numTrue = 0
var numFalse = 0
var boolArray = [true, true, false, true]

for index in boolArray.enumerate() {
  if index == false{
    numFalse++
  } else {
    numTrue++
  }
}

print("Count true: \(numTrue)")
print("Count false: \(numFalse)")

Solution

  • The code does not compile because enumerate is returning you a SequenceType in form (n, x).

    Change your code to the following:

    var numTrue = 0
    var numFalse = 0
    let boolArray = [true, true, false, true]
    
    //We are interested in value, ignoring the index
    for (_, value) in boolArray.enumerate()
    {
        if value == false
        {
            numFalse++
        }
        else
        {
            numTrue++
        }
    } 
    

    Output:

    Count true: 3
    Count false: 1