This is a toy example but it reduces exactly the situation I'm in:
class MyDataSource: UITableViewDiffableDataSource<String,String> {
var string : String?
init(string:String?) {
self.string = string
super.init(tableView: UITableView()) { (_, _, _) -> UITableViewCell? in
print(self.string) // error
return nil
}
}
}
I'm trying to make my table view data source self-contained, and my way of doing that (so far) is to subclass UITableViewDiffableDataSource. This works fine except when I try to give my subclass a custom initializer. The toy example shows the problem.
The way I want to populate the cell absolutely depends upon a value that can change later in the life of the data source. Therefore it cannot be hard-coded into the cell provider function. I cannot refer here simply to string
, the value that was passed in the initializer; I must refer to self.string
because other code is going to have the power to change this data source's string
instance property later on, and I want the cell provider to use that new value when that happens.
However, I'm getting the error "self captured by a closure before all members were initialized". That seems unfair. I did initialize my string
instance property before calling super.init
. So it does have a value at the earliest moment when the cell provider method can possibly be called.