Swift - 什么是向下转型?为什么我需要在 tableview 中向下转换单元格? [英] Swift - what is downcasting? why do i need to downcast the cell in tableview?
问题描述
下面的代码是在UItableview中显示单元格的名称.
The code below is to show the name of the cells in UItableview.
override func tableView(tableView: UITableView,
cellForRowAtIndexPath
indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")
as UITableViewCell
cell.textLabel!.text = "Spring \(indexPath.row + 1)"
return cell
}
存在编译错误,Xcode 建议我将行 'as' 更改为 'as!'-
There is a compiling error and Xcode suggests me to change the line 'as' into 'as!'-
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")
as! UITableViewCell
有人可以解释一下什么是沮丧以及为什么在这种情况下我们需要沮丧吗?
May someone explains what is downcast and why do we need to downcast in this case?
推荐答案
好的..让它变得非常简单.
OK..lets make it very simple.
上线:
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")
您正在访问tableView
的dequeueReusableCellWithIdentifier
方法,如果您查看文档,您可以看到返回类型是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
这篇关于Swift - 什么是向下转型?为什么我需要在 tableview 中向下转换单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!