ios - AnyObject 可以被视为普通对象吗?如何?

标签 ios swift xcode

我有任何对象

    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/

相关文章:

ios - 如何在我的选项卡栏 iOS 应用程序上呈现模态 UI 导航 View ?

ios - 通过 AVAssetDownloadTask/Session 下载后如何更新 AVURLAsset 的元数据?

ios - 本地址栏中只有前缀时,使 iphone webview 转到不同的网址

ios - _GSRegisterPurpleNamedPortInPrivateNamespace - 应用商店崩溃(附代码)

iphone - UIButton 导致 UITextField 字删除

ios - 我有一个类我想要一些方法转移到数组的对象

ios - Shopify iOS SDK - 将 BuyProductVariant 转换为 BuyProduct 的问题

ios - 如何将 CUPS 安装到 iOS 设备上?

ios - iOS UIButton 选中区域

ios - 使用 SwiftyJSON 的未解析标识符 JSON