如何在swift中将协议转换/转换为类?

时间:2015-02-25 15:58:36

标签: ios class swift protocols

很简单,我已经想到了;我只是想检查一个变量是否是一个类,并在可能的情况下将其强制转换为一个。

例如:

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 - 唯一标识符。

我尝试了一些事情来使演员阵容发生但是没有奏效:

    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;

这给了我没有错误并且运行正常。

2 个答案:

答案 0 :(得分:4)

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

var cellToReturn = cellProtocol as! UITableViewCell

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

var cellToReturn = cellProtocol as AnyObject as UITableViewCell

补充:事实证明这是Optional

的问题

在这种情况下,cellProtocolMyTableViewCellProtocol?。你必须先解开它,然后再施展。

尝试:

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

答案 1 :(得分:0)

如果您希望它只是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的协议的协议一致性(但您已经这样做了)。