【问题标题】:Cannot convert value of type 'Int' to expected argument type 'Int' in generic无法将类型“Int”的值转换为泛型中的预期参数类型“Int”
【发布时间】:2019-01-24 16:45:01
【问题描述】:

我创建了一个简单的协议,其中包含一个采用泛型参数的方法。

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

【问题讨论】:

    标签: swift generics


    【解决方案1】:
    func notify<Int>(data: Int, value: Int, at indexPath: IndexPath?) {
       buttonSelection.updateTag(tag:value, for:indexPath)
    }
    

    这不是您实现采用Int 的方法的方式。 &lt;Int&gt; 表示您有一个带有名为 Int 的参数的泛型方法。不是整数类型Int,而是泛型参数的名称,和&lt;T&gt;一样:

    如果你在协议中声明一个泛型方法,你不能只实现一种类型,你必须实现所有类型。

    您实际上可能希望使用具有关联类型而不是泛型的协议:

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

    【讨论】:

    • 哇!我用 抛弃了自己,是的,你对我的意图是正确的:具有关联类型的协议。谢谢!
    猜你喜欢
    • 2019-05-12
    • 2020-11-11
    • 2016-08-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    • 2017-01-09
    • 2017-02-08
    • 2018-10-01
    相关资源
    最近更新 更多