-1

I am in the process of converting my app from Objective C to Swift. I doing well in all areas with this exception. In my objective c file I have a UITableView that allows multiple selections. When the user selects a cell, information from that object is stored in an array. and when the user clicks the cell again, that object is removed. I am trying to figure out how this works in Swift 3 and I can add the object, but I just cannot seem to figure out how to remove that object from the array. Please advise. Below is my code from Objective C that I am trying to convert over.

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        RibbonsInfo *ribbonsInfo = [ribbonsArray objectAtIndex:indexPath.row];
        UITableViewCell *cell = [ribbonTableView cellForRowAtIndexPath:indexPath];
        if (ribbonTableView.allowsMultipleSelection == YES) {
            if(cell.accessoryType == UITableViewCellAccessoryNone) {
                cell.accessoryType = UITableViewCellAccessoryCheckmark;

                [selectedRibbons addObject:ribbonsInfo];

            }
            else {
                cell.accessoryType = UITableViewCellAccessoryNone;
                [selectedRibbons removeObject:ribbonsInfo];
            }
        }
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }

1 Answers1

0

With Swift, you can only remove items from an Array by using its index. So you need to get the index of that object inside that array, then call selectedRibbons.remove(at: index).

For example.

var array = Array<String>()

array.append("apple")

array.append("banana")

array.append("orange")

print(array) // ["apple", "banana", "orange"]

if let index = array.index(of: "banana") {

    array.remove(at: index)
}

print(array) // ["apple", "orange"]
Tristan Beaton
  • 1,742
  • 2
  • 14
  • 25