我有任何对象
var currentObject : AnyObject
它的值取决于 if 语句:
if sender.tag == 1 {
currentObject = object1()
}
else if sender.tag == 2 {
currentObject = object2()
}
.....
etc
numberOfRowsInSection 函数:
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return(currentObject.count)
}
cellForRowAt 函数:
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath) as UITableViewCell
let p = currentObject.item[indexPath.row]
cell.textLabel?.text = p.something
return(cell)
}
我想在 cellForRowAt 函数中使用这一行来从不同的对象中检索单元格内容
let p = currentObject.item[indexPath.row]
我收到一条错误消息:“AnyObject”不是“NSIndexPath”的子类型
我希望我的 AnyObject 被视为我已经分配给它的对象。
有什么建议吗?
最佳答案
AnyObject
可以被视为所有对象的“基类”。
如果你有:
let index: AnyObject = IndexPath(item: 0, section: 0)
您可以通过将其转换为所需的类型来使用它:
if let indexPath = index as? IndexPath {
// indexPath is type of IndexPath
}
并非所有 AnyObject
都可以是 IndexPath
,这就是转换失败的原因。
这是真正的基础学习。我建议你查看A Swift Tour by Apple .
关于ios - AnyObject 可以被视为普通对象吗?如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47389712/