为什么 Diffable 数据源对类和结构类型的处理方式不同?

问题描述

Diffable 数据源需要指定一个 SectionIdentifierType一个 ItemIdentifierType,并且这些类型必须符合 Hashable

据说它们必须符合 Hashable 以便数据源可以进行差异化。

那么为什么即使 == 和哈希函数相同,它的行为也会根据标识符类型是类还是结构而有所不同?或者甚至为类重写 === 函数,使其更像一个值类型?

示例:

import UIKit

public class DebugViewController: UIViewController {

    typealias SectionType = IntWrapper
    typealias ItemType = IntWrapper
    
    public class IntWrapper: Hashable {
        public static func == (lhs: DebugViewController.IntWrapper,rhs: DebugViewController.IntWrapper) -> Bool {
            lhs.number == rhs.number
        }
        public static func === (lhs: DebugViewController.IntWrapper,rhs: DebugViewController.IntWrapper) -> Bool {
            lhs.number == rhs.number
        }
        public func hash(into hasher: inout Hasher) {
            hasher.combine(number)
        }
        var number: Int
        
        init(number: Int) {
            self.number = number
        }
    }
    
    private var dataSource: UITableViewDiffableDataSource<SectionType,ItemType>!
    
    @IBOutlet var tableView: UITableView!
    
    public override func viewDidLoad() {
        super.viewDidLoad()

        tableView.register(UITableViewCell.self,forCellReuseIdentifier: "DefaultCell")
        
        dataSource = UITableViewDiffableDataSource<SectionType,ItemType>(tableView: tableView) { (tableView,indexPath,item) -> UITableViewCell? in
            let cell = tableView.dequeueReusableCell(withIdentifier: "DefaultCell")!
            cell.textLabel?.text = "\(item.number)"
            return cell
        }
        
        apply()
    }
    
    @IBAction func buttonTapped(_ sender: Any) {
        apply()
    }
    
    func apply() {
        var snapshot = NSDiffableDataSourceSnapshot<SectionType,ItemType>()
        
        let sections = [IntWrapper(number: 0)]
        let items = [IntWrapper(number: 1)]
        snapshot.appendSections(sections)
        sections.forEach { snapshot.appendItems( items,toSection: $0) }
        dataSource.apply(snapshot,animatingDifferences: true)
    }
}

如果 IntWrapper一个结构体,则在调用 apply() 时表视图不执行任何操作(apply() 基本上加载相同的数据)对我来说,这是预期的行为。

如果 IntWrapper一个类,则在调用 apply() 时重新加载表视图。此外,甚至没有调用 hash() 和 == 函数

除非有人可以访问源代码提示提示)或者除非我在示例中犯了一些错误,否则我认为无法回答这个问题。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)