jeudi 22 décembre 2016

Remove elements from Array if checkbox gets unchecked in swift?

let redundantArray = ["a", "r", "r", "a", "y"]

converted to distint Array using Set

let distinctArray = Array(Set(redundantArray))

distinctArray is displayed in UITableView 2nd section with selected checkboxes

If user unchecked any element then new array should be created with selected remaining elements. Suppose If I unchecked "r" element then new array with remaining elements should be created i.e., let newArray = ["a", "a", "y"] from redundantArray

My question is how to create new array with remaining selected checkboxes elements?

My code :

var preferedIndexPaths:[NSIndexPath] = []

To select all checkboxes, below code used -

for row in  0..<distinctArray.count {
    self.preferedIndexPaths.append(NSIndexPath(forRow: row, inSection:2))
}

if user select checkbox ( UIButton action ) then

self.preferedIndexPaths.append(indexPath)

else

self.preferedIndexPaths = self.preferedIndexPaths.filter(){$0 != indexPath}

if self.preferedIndexPaths.count > 0 {
 for indexPath in self.preferedIndexPaths {
let tempElement = distinctArray[indexPath.row]
let tempArr = redundantArray?.filter({
            $0 == tempElement
 })
for tempElement2 in tempArr {
                newArray?.append(preferedRestaurant)
            }
      }
}

When I tested my application in simulator from ascending order then its work fine but when I do same in descending order then elements are getting incremented.

What am I doing wrong? How to deal with this?




Aucun commentaire:

Enregistrer un commentaire