簡體   English   中英

如何快速從協議轉換/廣播到類?

[英]How to convert/cast from a protocol to a class in swift?

很簡單,我曾想過; 我只想檢查變量是否為一類,並在可能的情況下將其強制轉換為一個。

例如:

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-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開始,您必須將其AnyObjectAnyObjectAny ,然后轉換為UITableViewCell 我認為這是一種錯誤。

var cellToReturn = cellProtocol as AnyObject as UITableViewCell

添加:事實證明這是Optional問題

在這種情況下, cellProtocolMyTableViewCellProtocol? 您必須先將其拆開,然后再進行投射。

嘗試:

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

如果只希望它是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協議的協議一致性(但是您已經完成了此操作)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM