6.0.1 and Table changes “UILabel? does not have a member named 'text”

谁都会走 提交于 2019-12-23 07:39:37

问题


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.



来源:https://stackoverflow.com/questions/25964901/6-0-1-and-table-changes-uilabel-does-not-have-a-member-named-text

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!