Arko
Arko

Reputation: 65

While loop not checking correctly in Swift

Currently I have a while statement that loops through all cells below that are of a lower padding level and is supposed to remove said cells. Currently the below statement goes through about 3 of them then stops even though further cells meet the conditions.

if isExpanded[indexPath.item] //if already expanded remove
{
    var t = 1

    while (comment.paddingLevel != commentsData[indexPath.row + t].paddingLevel)
    {
        isExpanded.removeAtIndex(indexPath.row + t)

        preRenderedText.removeAtIndex(indexPath.row + t)
        commentsData.removeAtIndex(indexPath.row + t)

        var path = NSIndexPath(forItem: indexPath.row + t, inSection: 0)
        t++
        delpaths.append(path)        
    }
}

Upvotes: 0

Views: 142

Answers (1)

Paulw11
Paulw11

Reputation: 115041

You are mutating the isExpanded array by deleting items from it - this means that the index for the next item is going to reduce by one, but you increment t regardless. An NSMutableIndexSet is probably a better data structure to use for isExpanded rather than an array.

An NSMutableIndexSet stores a set of integer indices - In this case it would be your item values. Then you can use the set's contains(item) method to quickly get an answer as to whether a particular index is in the set or not.

Upvotes: 2

Related Questions