6.0.1 and Table changes “UILabel? does not have a

2019-06-15 10:29发布

问题:

I'm working my way through the Swift table demos, and all of them seem have this same error message under 6.0.1. Not sure how to tackle this:

回答1:

try this:

cell.textLabel!.text = self.tableData[indexPath.row]

And read this article about optionals here: Optionals in Swift

Update:

A better approach is now to use:

cell.textLabel?.text = self.tableData[indexPath.row]


回答2:

In Xcode 6.1.1 you have to unwrap both the cell and textLabel:

cell!.textLabel!.text = "your text"



回答3:

If you look up the textLabel property documentation here, you will find it defined as:

var textLabel: UILabel? { get }

This indicates that the property is an Optional. That means that it might contain a valid value or it might be a nil. If you are 100% sure that your cell will have this textLabel populated, then you can use the method suggested by derdida i.e:

cell.textLabel!.text = self.tableData[indexPath.row]

However, as Patrick Lynch rightly pointed out, you are just setting yourself up for future run-time crashes (time bombs) if you do this to all Optionals you encounter. The best practice is to write code that will gracefully handle the case whereby an Optional is nil. In that case, the whole expression evaluates to nil. Something like this:

cell.textLabel?.text = self.tableData[indexPath.row]

Although I have no infographic for this topic, a very good write-up exists here and will get you up to speed in no time. I hope that helps.



标签: ios swift xcode6