ios - Swift:如何将通用协议作为另一个协议的参数传递
问题描述
我想将通用协议作为另一个协议的参数传递。
protocol OperationDelegate {
associatedtype T
func onOperationFinished(result:Array<T>)
func onOperationError(error:OperationError, errorMessage:String)
}
protocol ResultDelegate {
func findResult(query: String,odelegate: OperationDelegate<MyOwnDataType>)
}
如何将通用协议作为另一个协议的参数传递
我收到以下错误
Protocol 'OperationDelegate' can only be used as a generic constraint because it has Self or associated type requirements
解决方案
protocol OperationDelegate {
associatedtype T
func onOperationFinished(result:Array<T>)
func onOperationError(error: Error, errorMessage:String)
}
protocol ResultDelegate {
func findResult<OpDelegate: OperationDelegate>(query: String, odelegate: OpDelegate)
}
//添加了一些 PlayGround 作品
class ResultsFinder: ResultDelegate {
func findResult<OpDelegate>(query: String, odelegate: OpDelegate) where OpDelegate : OperationDelegate {
print(#function)
// Do some operations
let s1 = Student()
s1.name = "one"
let s2 = Student()
s2.name = "two"
let addressList = [s1,s2]
odelegate.onOperationFinished(result: addressList as! [OpDelegate.T])
}
}
还
class ResultDisplay: OperationDelegate {
typealias T = Student
func onOperationFinished(result: [Student]) {
// Display address
print(#function)
}
func onOperationError(error: Error, errorMessage: String) {
// Display error
print(#function)
}
}
类主函数{
let resultDisplay = ResultDisplay()
let finder = ResultsFinder()
func start() {
print(#function)
finder.findResult(query: "Sridhar", odelegate: resultDisplay)
}
}
let main = Mainfunction()
main.start()
推荐阅读
- c# - 等效于“Into”的 Linq 方法
- android - Android Kotlin 将数据从 NavController 传递到最后一个 Fragment
- python-3.x - 在 eltima com 端口上进行 Pyserial 读取
- jquery - 将php时间戳与Jquery进行比较
- javascript - 反应原生 - 无法水平居中我的滚动视图
- mysql - 我想找出查询哪个 group by 后跟 order by
- python - 软件包安装在 conda 中,但未找到模块。这怎么可能?
- sql-server - 如何在 SQL Server 中使用 ORDER BY 和 UNION ALL?
- angular - ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。表单控件
- angular - 在 Angular 中初始化之前无法访问模块