gpt4 book ai didi

ios - 如何快速从协议(protocol)转换/转换为类?

转载 作者:搜寻专家 更新时间:2023-11-01 06:23:36 25 4
gpt4 key购买 nike

我原以为很简单;我只想检查一个变量是否是一个类,并在可能的情况下将其转换为一个类。

例如:

var cellProtocol:MyTableViewCellProtocol? = nil
cellProtocol = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier, forIndexPath: indexPath) as MyTableViewCell

如何将单元格显式转换为 UITableViewCell?

继承如下:

class MyTableViewCell: UITableViewCell, MyTableViewCellProtocol {
//....
}


@objc protocol MyTableViewCellProtocol: class, NSObjectProtocol {
func configureCell()
}

那个协议(protocol)定义是我试图解决这个问题的结果。我原来的那个没有@objc 标签或class-only 标识符。

我尝试了一些方法来实现转换,但没有成功:

    var cellToReturn = cellProtocol as UITableViewCell

这不会编译,因为 UITableViewCell 没有显式继承自 MyTableViewCellProtocol

    var cellToReturn = cellProtocol as AnyObject as UITableViewCell

这在运行时失败,因为 cellProtocol 无法转换为 AnyObject

我还没有能够让 unsafeBitCast 正常工作,但这是我一直在探索的另一种可能性。

请注意,这在 Obj-C 中确实有效。

id<MyTableViewCellProtocol> cellProtocol = cell;
[cellProtocol configureCell];
UITableViewCell *cellCast = (UITableViewCell *)cellProtocol;

这没有给我任何错误并且运行良好。

最佳答案

使用 Swift 1.2/Xcode 6.3 Beta,编译:

var cellToReturn = cellProtocol as! UITableViewCell

从 Swift 1.1 开始,您必须将其转换为 AnyObjectAny,然后是 UITableViewCell。我认为这是一种错误。

var cellToReturn = cellProtocol as AnyObject as UITableViewCell

ADDED:原来是Optional

的问题

在这种情况下,cellProtocolMyTableViewCellProtocol?。你必须先打开它,然后再转换。

尝试:

var cellToReturn = cellProtocol! as AnyObject as UITableViewCell
// ^

关于ios - 如何快速从协议(protocol)转换/转换为类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28723625/

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