sakoaskoaso
sakoaskoaso

Reputation: 347

Swift: Property 'self.tableView' not initialized at super.init call

I have a class in my Swift code which designs UICollectionViewCells

class PostCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource { 

    let tableView: UITableView!

    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .white

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellReuseIdentifier")
        tableView.delegate = self
        tableView.dataSource = self

        designCell()
    }
}

I need to have a UITableView in the cell thus i added UITableViewDelegate, UITableViewDataSource classes,but this returns me following error

Property 'self.tableView' not initialized at super.init call What may be the problem and how can i initialize tableView?

Upvotes: 0

Views: 533

Answers (2)

vadian
vadian

Reputation: 285072

According to the initialization rules all stored properties must be initialized before calling an init method of the super class. Declaring a property as implicit unwrapped optional does not initialize the property.

Declare tableView as non-optional and initialize it before the super call

class PostCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource {

    let tableView: UITableView

    override init(frame: CGRect) {
        tableView = UITableView(frame: frame)
        super.init(frame: frame)
        backgroundColor = .white

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellReuseIdentifier")
        tableView.delegate = self
        tableView.dataSource = self

        designCell()
    }
}

Upvotes: 2

Hussain Shabbir
Hussain Shabbir

Reputation: 15015

You need to either create and connect the outlet of UITableView or create it programmatically

let tableView = UITableView(frame: yourFrame)

Upvotes: 1

Related Questions