gpt4 book ai didi

swift - 无法将类型 'Int' 的值转换为泛型中预期的参数类型 'Int'

转载 作者:搜寻专家 更新时间:2023-11-01 06:11:55 25 4
gpt4 key购买 nike

我创建了一个简单的协议(protocol),其中包含一个采用通用参数的方法。

protocol NotifyDataSelected: class {
func notify<T>(data: T, value:T, at indexPath: IndexPath?)
}

我已经实现了如下所示的协议(protocol)功能:

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

编译器发出一个实际上自相矛盾的错误: enter image description here

为什么?

这是使用 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> 相同:

enter image description here

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

您可能真的想使用具有关联类型而不是泛型的协议(protocol):

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

关于swift - 无法将类型 'Int' 的值转换为泛型中预期的参数类型 'Int',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54351554/

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