Reputation: 133
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?
Upvotes: 3
Views: 1874
Reputation: 7363
Because the non optional type cannot be compared with nil
(Only optional variables contains nil
value). Like if you want to check nil
then just use that way. i implemented it in Playground
let tableView = UITableView()
let index = NSIndexPath()
var cell:UITableViewCell! = tableView.dequeueReusableCellWithIdentifier("")
//then make check for nil if you want
if (cell == nil) {
print("its nil")
} else {
print("not nil")
}
Upvotes: 0
Reputation: 3894
According to Apple docs, dequeReusableCellWithIdentifier
returns an optional value :
func dequeueReusableCellWithIdentifier(_ identifier: String) -> UITableViewCell?
But in your code, you explicitly unwrap this value because your cell object is an UITableViewCell
object.
You should use - dequeueReusableCellWithIdentifier:forIndexPath:
: its return value is not optional thus you don't have to unwrap your cell.
Upvotes: 1
Reputation: 4676
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:)
.
Upvotes: 3