I am trying to create UITableViewCell type variable with swift, these are my codes:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dwarves.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(simpleTableIdentifier)! as UITableViewCell
if (cell == nil) {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: simpleTableIdentifier)
}
cell.textLabel?.text = dwarves[indexPath.row]
return cell
}
In 7th line if (cell == nil), it gives me an error that Value of type 'UITableViewCell' can never be nil, comparison isn't allowed. It can't be replaced by if ( !cell ). How should I fix the codes?
If you really want to use the outdated method tableView.dequeueReusableCellWithIdentifier(_:) you can do it like this:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(simpleTableIdentifier) ?? UITableViewCell(style: .Default, reuseIdentifier: simpleTableIdentifier)
cell.textLabel?.text = dwarves[indexPath.row]
return cell
}
But you should preferably use dequeueReusableCellWithIdentifier(_:forIndexPath:) which never returns nil.
It is used along with registerClass(_:forCellReuseIdentifier:) and registerNib(_:forCellReuseIdentifier:).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With