Oleksandr Matrosov
Oleksandr Matrosov

Reputation: 27187

Swift. Can't change structure's property, received form array

I have a problem with updating my array of generic structures which are [SelectableItem] in the example below.

Quick 40 seconds video screencast with a problem.

So I have an UITableView with datasource of [SelectableItem]. At first time when I init this array where I specify name and selected states, table view shows data correctly. But when I try to select SelectableItem and switch isSelected Bool state to true and reload data then, the source SelectableItem isSelected property is still false when cell try to get it via the same getModelAt func.

protocol Selectable {
    var isSelected: Bool { get set }
}

struct SelectableItem: Selectable {

    var isSelected: Bool
    let name: String
}

func getModelAt(_ indexPath: IndexPath) -> T {
        return isSearchActive ? searchResults[indexPath.item] : models[indexPath.item]
    }

@objc(tableView:didSelectRowAtIndexPath:) func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        if var model = strongDataSource?.getModelAt(indexPath) {
            model.isSelected = !model.isSelected
            tableView.reloadData()
        }
    }

on this line model.isSelected = !model.isSelected all goes well and I see name of model and how model.isSelected switched to another value (from false to true for example and form true to false).

My assumption that as I use structures instead of classes, maybe my getModelAt returns to me a model by value from array not by reference. But I am not 100% sure. Or maybe something wrong with Protocol get set

Not sure if it will be helpful to understand my question, but I used this link to implement search functionality and I just extended it with selection functionality. So all works good excluding assignment new values for isSelected property of structure instance.

Upvotes: 0

Views: 166

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100543

For a struct assignment means copying and changing it does't affect the main reference

if var model = strongDataSource?.getModelAt(indexPath) {

so you need to make SelectableItem a class

Upvotes: 1

Related Questions