Search code examples
swiftuitableviewgenericstypesgeneric-programming

Cannot assign value of type 'GenericTableViewController<T, U>' to type 'GenericTableViewController<GenericTableViewCell<_>, _>'


I have my generic table view controller

class GenericTableViewController<T: GenericTableViewCell<U>, U>: UITableViewController {
    // some stuff
}

with cellForRowAt indexPath

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? GenericTableViewCell<U>
        cell?.controller = self // Cannot assign value of type 'GenericTableViewController<T, U>' to type 'GenericTableViewController<GenericTableViewCell<_>, _>'
        // some stuff
        return cell ?? GenericTableViewCell<U>(style: .default, reuseIdentifier: nil)
    }

and in my generic table view cell class I have a property controller that represents the generic table view controller itself:

class GenericTableViewCell<U>: UITableViewCell {
    var item: U?
    var controller: GenericTableViewController<GenericTableViewCell<U>, U>

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        controller = GenericTableViewController()
        super.init(style: style, reuseIdentifier: reuseIdentifier)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    @objc func handleMarkAsFavorite() {
        controller.favoriteCell(cell: self)
    }

    lazy var starButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(#imageLiteral(resourceName: "fav_star"), for: .normal)
        button.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
        button.addTarget(self, action: #selector(handleMarkAsFavorite), for: .touchUpInside)
        return button
    }()    
}

I wanted to link my table view cell with table view controller to favorite cells and then present them in another controller (aka favorites). However, I get error telling me that it cannot connect cell with its controller because of type issue

Cannot assign value of type 'GenericTableViewController<T, U>' to type 'GenericTableViewController<GenericTableViewCell<_>, _>'

I'm new to generic so I'll be glad to any help!


Solution

  • You can cast self as below,

    cell?.controller = self as! GenericTableViewController<GenericTableViewCell<U>, U>