The count in my For loop is not incrementing

1.9k views Asked by At

When running my code, I am getting a number of 1's printing to the console rather than 1,2,3,4,5....

Some help with why this is happening would be great, I'm having trouble figuring it out.

The idea is to loop through the Calendar names until finding the 'Travel' calendar.

func checkCalendarExists(){
    var eventCalendars = store.calendarsForEntityType(EKEntityTypeEvent) as [EKCalendar]

    for i in eventCalendars {

        var count = 0
        var calendarCount = eventCalendars.count

        if i.title != "Travel" && count != calendarCount
        {
            ++count
            println(count)
        }

        else if i.title == "Travel"
        {
            // do something
        }
        else
        {
           aMethod()
        }

    }
}
3

There are 3 answers

0
ALXGTV On BEST ANSWER

Your count variable is not being incremented because it is declared inside the loop and initialized to the value zero at the beginning of each iteration. For your code to work as expected you have to move var count = 0 outside the for loop.

2
user3337714 On

Your count variable does get incremented, but it resets to zero every time the for loop runs its sequence.

It's always advised to declare and assign incrementing variables outside loops.

Please change your code to (I am initializing var count = 0 before the loop)

    func checkCalendarExists(){
        var eventCalendars = store.calendarsForEntityType(EKEntityTypeEvent) as [EKCalendar]

        var count = 0
        for i in eventCalendars {

            var calendarCount = eventCalendars.count
        ......
        ......
        ......
        else
        {
           aMethod()
        }
    }
}
0
Antonio On

ALXGTV's answer explains why you have that unexpected behavior.

Your code can be optimized though - rather than manually handling a counter variable, I recommend using the enumerate function, which returns a (index, value) at each iteration:

for (index, calendar) in enumerate(eventCalendars) {
    ...
}

Also this variable:

var calendarCount = eventCalendars.count

is populated at each iteration, always with the same value. It would be more efficient if it is moved before the loop, making it immutable:

let calendarCount = eventCalendars.count
for (index, calendar) in enumerate(eventCalendars) {
    ...
}

Last, I would prefer using a flag for the not found condition, handling it outside the loop:

func checkCalendarExists() {
    var eventCalendars = store.calendarsForEntityType(EKEntityTypeEvent) as [EKCalendar]    
    var found = false
    let calendarCount = eventCalendars.count
    for (index, calendar) in enumerate(eventCalendars) {
        if calendar.title == "Travel" {
            // do something
            found = true
            break // This stops the loop
        } else {
            println(index + 1)
        }
    }

    if !found {
        aMethod()
    }
}