首页 > 解决方案 > 无法将类型“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

标签: swiftgenerics

解决方案


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

推荐阅读