Ios 如何在swift中将协议转换/转换为类?
我想这很简单;我只想检查一个变量是否是一个类,如果可能的话,将它转换为一个类 例如:Ios 如何在swift中将协议转换/转换为类?,ios,class,swift,protocols,Ios,Class,Swift,Protocols,我想这很简单;我只想检查一个变量是否是一个类,如果可能的话,将它转换为一个类 例如: var cellProtocol:MyTableViewCellProtocol? = nil cellProtocol = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier, forIndexPath: indexPath) as MyTableViewCell 如何将单元格显式转换为UITableViewCell 继承情况如下: cla
var cellProtocol:MyTableViewCellProtocol? = nil
cellProtocol = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier, forIndexPath: indexPath) as MyTableViewCell
如何将单元格显式转换为UITableViewCell
继承情况如下:
class MyTableViewCell: UITableViewCell, MyTableViewCellProtocol {
//....
}
@objc protocol MyTableViewCellProtocol: class, NSObjectProtocol {
func configureCell()
}
协议定义是我试图解决这个问题的结果。我的原始版本中没有@objc
标记,也没有仅包含类的标识符
我尝试了几件事让演员阵容成真,但都没有成功:
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;
id cellProtocol=cell;
[cellProtocol configureCell];
UITableViewCell*cellCast=(UITableViewCell*)cellProtocol;
这不会给我任何错误,而且运行良好。如果希望它只是一个MyTableViewCellProtocol
,应该在as
子句中使用它。如果需要条件强制转换,请使用If let
if let cellProtocol = <dequeue> as? MyTableViewCellProtocol {
// You're an object that conforms to MyTableViewCellProtocol.
if let mycell = cellProtocol as? MyTableViewCell {
// You're a MyTableViewCell object
if let cell = cell as? UITableViewCell {
// You're a UITableViewCell object
}
}
}
如果让cellProtocol=as?MyTableViewCellProtocol{
//您是一个符合MyTableViewCellProtocol的对象。
如果让mycell=cellProtocol as?MyTableViewCell{
//您是MyTableViewCell对象
如果let cell=cell as?UITableViewCell{
//您是UITableViewCell对象
}
}
}
请记住,您只能在指定为@objc
的协议上检查协议一致性(但您已经这样做了)。使用Swift 1.2/Xcode 6.3 Beta,这将编译:
var cellToReturn = cellProtocol as! UITableViewCell
从Swift 1.1开始,您必须将其强制转换为AnyObject
或Any
,然后再转换为UITableViewCell
。我认为这是一种错误
var cellToReturn = cellProtocol as AnyObject as UITableViewCell
补充:原来这是一个可选的问题
在这种情况下,cellProtocol
是MyTableViewCellProtocol?
。你必须先把它打开,然后再施展
尝试:
我想这是一种避免演员出演的方法。但是,有没有办法进行实际的转换?您想要哪种转换?将MyTableViewCellProtocol类型的var转换为UITableViewCellAs关键字需要是as?但即使这样,第二个也无法编译。确切的错误是类型“UITableViewCell”不符合协议MyTableViewCellProtocol。我想我在问题中表达得不好,但这就是我整个问题的内容。我的手机是从UITableViewCell继承的,我只是在转录时弄糟了,对不起!很高兴知道它在swift 1.2中工作!
var cellToReturn = cellProtocol! as AnyObject as UITableViewCell
// ^