【问题标题】:Swift. Can't change structure's property, received form array迅速。无法更改结构的属性,收到表单数组
【发布时间】:2019-09-28 19:02:57
【问题描述】:

我在更新我的泛型结构数组时遇到问题,在下面的示例中是 [SelectableItem]

Quick 40 seconds video screencast with a problem.

所以我有一个UITableView,其数据源为[SelectableItem]。第一次在我指定名称和选定状态的地方初始化这个数组时,表格视图会正确显示数据。但是当我尝试选择SelectableItem 并将isSelected Bool 状态切换为true 并重新加载数据时,源SelectableItemisSelected 属性仍然是false,当单元格尝试通过相同的getModelAt 函数获取它时.

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()
        }
    }

在这条线上 model.isSelected = !model.isSelected 一切顺利,我看到了模型的名称以及 model.isSelected 如何切换到另一个值(例如从 false 到 true 以及从 true 到 false 的形式)。

我的假设是,当我使用结构而不是类时,我的 getModelAt 可能会从数组中按值而不是通过引用返回给我一个模型。但我不是 100% 确定。或者Protocol get set可能有问题

不确定是否有助于理解我的问题,但我使用此 link 来实现搜索功能,并且我只是使用选择功能对其进行了扩展。因此,除了为结构实例的 isSelected 属性分配新值之外,一切正常。

【问题讨论】:

    标签: ios swift struct swift-protocols


    【解决方案1】:

    对于struct 赋值意味着复制和更改它不会影响主引用

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

    所以你需要将SelectableItem 设为一个类

    【讨论】:

      猜你喜欢
      • 2015-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 2014-06-04
      • 2016-11-04
      • 1970-01-01
      相关资源
      最近更新 更多