6.0.1 and Table changes “UILabel? does not have a

2019-06-15 10:10发布

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:

enter image description here

标签: ios swift xcode6
3条回答
疯言疯语
2楼-- · 2019-06-15 10:30

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.

查看更多
疯言疯语
3楼-- · 2019-06-15 10:31

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

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

查看更多
走好不送
4楼-- · 2019-06-15 10:36

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]
查看更多
登录 后发表回答