gpt4 book ai didi

swift - 无法检查模型是否符合 Swift 协议(protocol)

转载 作者:行者123 更新时间:2023-11-28 06:15:16 25 4
gpt4 key购买 nike

我有协议(protocol):

protocol SelectingRowProtocol : class {

func selectItemAtIndexPath(row: Int)
}

和模型:

class HRVacanciesViewModel :  BaseModel, CDTableAdapterViewModel, SelectingRowProtocol {


weak var selectingRowDelegate : SelectingRowProtocol?

/* Selecting */

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

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

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

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

为什么会这样?

最佳答案

You can try making the protocol method as optional in order to avoid forced wrapping

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

And you can check if your viewmodel conforms to protocol like this:-

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)
}
}

关于swift - 无法检查模型是否符合 Swift 协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45329214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com