无法检查模型是否符合协议Swift

时间:2017-07-26 14:02:33

标签: swift

我有协议:

protocol SelectingRowProtocol : class {

    func selectItemAtIndexPath(row: Int)
}

模特:

class HRVacanciesViewModel :  BaseModel, CDTableAdapterViewModel, SelectingRowProtocol {


weak var selectingRowDelegate : SelectingRowProtocol?

/* Selecting */

func selectItemAtIndexPath(row: Int) {
  print("selected")
}

但是当我尝试检查时,如果模型符合协议,则评估为false:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    if let model = self.viewModel as? SelectingRowProtocol {
        //currentVC responds to the MyCustomProtocol protocol =]
    }
}

为什么会这样?

1 个答案:

答案 0 :(得分:1)

  

您可以尝试将协议方法设为可选,以避免   强制包装

@objc protocol SelectingRowProtocol : class {
  optional func selectItemAtIndexPath(row: Int)
}
  

您可以检查您的viewmodel是否符合以下协议: -

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  if self.viewModel is SelectingRowProtocol { //Should returns true
    //currentVC responds to the MyCustomProtocol protocol =]
//now call like this
(self.viewModel as? SelectingRowProtocol)?.selectItemAtIndexPath?(row: indexPath.row)
  }
}