No exemplo de código a seguir
import UIKit
struct Language: Hashable {
let name: String
}
enum Section {
case main
}
class ViewController: UIViewController, UITableViewDelegate {
var tableView: UITableView!
private typealias DataSource = UITableViewDiffableDataSource<Section, Language?>
private var dataSource: DataSource!
override func viewDidLoad() {
super.viewDidLoad()
// Set up the table view
tableView = UITableView(frame: view.bounds)
view.addSubview(tableView)
// Register a simple cell
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
// Set up the data source
dataSource = DataSource(tableView: tableView) { tableView, indexPath, language in
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
// Check if the language is nil and configure the cell accordingly
if let language = language {
cell.textLabel?.text = language.name
} else {
cell.textLabel?.text = "No Language"
}
return cell
}
// Set up the snapshot with some sample data including nil
var snapshot = NSDiffableDataSourceSnapshot<Section, Language?>()
snapshot.appendSections([.main])
snapshot.appendItems([Language(name: "English"), nil, Language(name: "Spanish"), Language(name: "French")])
// Apply the snapshot to the data source
dataSource.apply(snapshot, animatingDifferences: true)
tableView.delegate = self
}
}
Estou recebendo erro de tempo de execução
Could not cast value of type 'NSNull' (0x1ec78e900) to 'xxx.Language' (0x1008e0468).
Não é UITableViewDiffableDataSource
compatível nil
? Não consigo encontrar https://developer.apple.com/documentation/uikit/uitableviewdiffabledatasource falando sobre essa limitação.
Obrigado.
A documentação para
NSDiffableDataSourceSnapshot
estados:nil
não pode satisfazer este requisito.Como
UITableView
é Objective-C, onil
foi traduzido para o singleton especialNSNull
que também não pode satisfazer esse requisito.NSNull
também não pode ser convertido para uma instância deLanguage
, que é o erro que você está recebendo.Embora a documentação não declare explicitamente que você não pode adicionar
nil
, o requisito de que os itens tenham identificadores exclusivos implica fortemente isso.Na verdade, usar um opcional como seu tipo de item é o erro que deveria ser sinalizado. Isso não faz sentido. Seu snapshot são os itens que existem. Se um item não existe, você simplesmente não o adiciona ao snapshot
Embora o motivo do erro que você obtém possa não ser imediatamente óbvio e seja melhor que o erro de declarar um tipo opcional como seu tipo de item seja sinalizado em tempo de compilação, o comportamento parece razoável nas circunstâncias.