Creating a UITableView Cell in Swift

I am trying to create a UITableViewCell with a quick, in my delegate method cellForRowAtIndexPath,

the code is simple, as in Objective-c, just trying to quickly transform the language.

I get an error in this line

var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as UITableViewCell if(cell == nil) { let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle,reuseIdentifier:cellIdentifier) } 

UITableViewCell error does not convert to "MirrorDisposition"

I was looking for examples, the code was like this:

 if !cell {let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle,reuseIdentifier:cellIdentifier) } 

but also gives an error.

What am I doing wrong?

+6
source share
2 answers

As of the latest beta (beta 6), optional types cannot be compared to nil .

Therefore, you must declare your Var cell as optional.

Something like this will work correctly (from my head - I don't have Xcode in front of me):

 //declare a tableViewCell as an implicitly unwrapped optional... var cell:UITableViewCell! = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell //you CAN check this against nil, if nil then create a cell (don't redeclare like you were doing... if(cell == nil) { cell = UITableViewCell(style: UITableViewCellStyle.Subtitle,reuseIdentifier:cellIdentifier) } 
+11
source

It is best to use a more modern method that always returns the cell (if you use a storyboard or register a nib or class for the cell)

 let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as UITableViewCell 

Since the method always returns a cell, it is not optional, and there is no need to check for zero.

+9
source

Source: https://habr.com/ru/post/974071/


All Articles