gpt4 book ai didi

Swift:是否可以使用变量作为自定义类名?

转载 作者:行者123 更新时间:2023-11-30 10:12:58 24 4
gpt4 key购买 nike

我尝试将 CoreData 变量用于我的大部分应用程序代码,但无法将它们用于自定义类的名称。这是我的代码示例:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> CREWWorkCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellName) as! CREWWorkCell

我想为 CREWWorkCell 使用字符串。这可能吗?

最佳答案

UITableViewController 没有返回您可以覆盖的 CREWWorkCell 的函数。使用默认的 UITableViewCell 作为返回值,自定义单元格一切正常。

在您的 UITableViewController 类中使用以下函数:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // Note that the return value is UITableViewCell and not CREWWorkCell

//get the class name from the database and put it in a variable called myClassName. Then

if myClassName == "CREWWorkCell" {
let cell : CREWWorkCell = tableView.dequeueReusableCellWithIdentifier("cell identifier 1", forIndexPath: indexPath) as! CREWWorkCell //of course you should cast to your custom class to be able to use it
return cell
} else if myClassName == "AnotherCellClass" {
let cell : AnotherCellClass = tableView.dequeueReusableCellWithIdentifier("cell identifier 2", forIndexPath: indexPath) as! AnotherCellClass
return cell
}

//do the same if you have other custom classes etc...

return UITableViewCell()
}

使用 Swift,你无法转换为动态类型(看看 here )。因此,您无法转换为放入变量中的类型,例如:

var myClassName = CREWWorkCell.self

var myClassName = CREWWorkCell().dynamicType

因为 myClassName 将在运行时评估,换句话说,它是一个动态类型。但是转换运算符期望其右侧是一个静态类型,这是一种已知的类型,不需要在运行时进行评估。此功能允许 Swift 强制执行类型安全。

我建议您以更简单的方式重新考虑创建自定义单元格的方式。

关于Swift:是否可以使用变量作为自定义类名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31895879/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com