很简单,我想,我只想检查变量是否是类,并在可能的情况下将其转换为类。
例如:
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标记或class-only标识符。
我尝试了几种方法来让演员们成功,但这并没有奏效:
var cellToReturn = cellProtocol as UITableViewCell这不能编译,因为UITableViewCell没有显式地从MyTableViewCellProtocol继承。
var cellToReturn = cellProtocol as AnyObject as UITableViewCell这在运行时失败,因为cellProtocol无法转换为AnyObject。
我还没能让unsafeBitCast开始工作,但这是我一直在探索的另一种可能性。
只是注意一下,这在Obj中是有效的。
id<MyTableViewCellProtocol> cellProtocol = cell;
[cellProtocol configureCell];
UITableViewCell *cellCast = (UITableViewCell *)cellProtocol;这给了我没有错误,运行良好。
发布于 2015-02-25 16:20:34
使用Swift 1.2 / Xcode 6.3 Beta,它编译:
var cellToReturn = cellProtocol as! UITableViewCell从SWIFT1.1开始,您必须将其转换为AnyObject或Any,然后是UITableViewCell。我觉得这是一种虫子。
var cellToReturn = cellProtocol as AnyObject as UITableViewCell补充:原来这是Optional的一个问题
在这种情况下,cellProtocol是MyTableViewCellProtocol?。你必须先拆开它,然后再投。
尝试:
var cellToReturn = cellProtocol! as AnyObject as UITableViewCell
// ^发布于 2015-02-25 16:02:34
如果您只希望它是一个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
}
}
}请记住,您只能在指定为@objc的协议上检查协议一致性(但您已经这样做了)。
https://stackoverflow.com/questions/28723625
复制相似问题