swift - 无法将类型“Int”的值转换为泛型中的预期参数类型“Int”
问题描述
我创建了一个简单的协议,其中包含一个采用泛型参数的方法。
protocol NotifyDataSelected: class {
func notify<T>(data: T, value:T, at indexPath: IndexPath?)
}
我已经实现了如下所示的协议功能:
extension MainButtons: NotifyDataSelected {
func notify<Int>(data: Int, value: Int, at indexPath: IndexPath?) {
buttonSelection.updateTag(tag:value, for:indexPath)
}
}
updateTag 的签名是:
func updateTag(tag:Int, for indexPath:IndexPath) {
}
为什么?
这是使用 Xcode 10 和 Swift 4.2
解决方案
func notify<Int>(data: Int, value: Int, at indexPath: IndexPath?) {
buttonSelection.updateTag(tag:value, for:indexPath)
}
这不是您实现采用Int
. 这<Int>
意味着您有一个带有名为Int
. 它不是整数类型Int
,而是泛型参数的名称,与<T>
:
如果你在协议中声明一个泛型方法,你不能只实现一种类型,你必须实现所有类型。
您实际上可能想要使用具有关联类型而不是泛型的协议:
protocol NotifyDataSelected: class {
associatedtype T
func notify(data: T, value:T, at indexPath: IndexPath?)
}
extension MainButtons: NotifyDataSelected {
typealias T = Int
func notify(data: Int, value: Int, at indexPath: IndexPath?) {
}
}
推荐阅读
- python - 基于带有循环的模式匹配两个列表的元素
- sql - 使用 VBA 将表从 sql server 导出到访问表
- javascript - jQuery 平滑滚动以在移动设备上使用固定菜单锚定
- elasticsearch - SQL Server 数据库 > Logstash > Elasticsearch:将与同一实体相关的结果集记录映射到同一 ES 文档
- android - 安卓 Facebook 登录。防止按钮更改为“注销”
- flutter - 如何使用 Flutter Web 将数据保存在浏览器的 cookie 中?
- java - 使用 Maven Shade 构建应用程序 jar 时,排除所有 META-INF/versions 目录/文件是否安全?
- amazon-dynamodb - 查询 DynamoDB 表以按创建日期获取前 100 条记录的顺序
- excel - 记住位于另一列的一列中的公式的前一个值
- python-3.x - 如何将生成的 AsyncResult 传递给 FastAPI python 中的其他 API