且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Swift - 什么是向下转型?为什么我需要在 tableview 中向下转换单元格?

更新时间:2022-06-06 21:53:15

好的..让它变得非常简单.

OK..lets make it very simple.

上线:

let cell = tableView.dequeueReusableCellWithIdentifier("Cell")

您正在访问tableViewdequeueReusableCellWithIdentifier方法,如果您查看文档,您可以看到返回类型是AnyObject?.

You are accessing the method dequeueReusableCellWithIdentifier of tableView, if you look at the documentation you can see the return type is AnyObject?.

现在假设您要访问 textLabel 属性为

Now suppose you want to access the textLabel property as

cell.textLabel!.text = "Spring \(indexPath.row + 1)"

你不能这样做..因为在 AnyObject 类型上没有任何 textlabel.

You cannot do it..because there is no any textlabel on AnyObject the type.

因此,您正在向下转换以强制编译器更具体的类 UITableViewCell,如下所示,因为稍后您将尝试访问文本标签属性:

So, you are downcasting to force compiler more specific class, UITableViewCell, as below because later you are trying to access text label property:

let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell