gpt4 book ai didi

具有泛型方法的 Swift 协议(protocol) : invalid redeclaration of implementation

转载 作者:行者123 更新时间:2023-11-28 09:39:08 26 4
gpt4 key购买 nike

我正在 Swift 中玩一些协议(protocol)/通用的东西,我很好奇为什么以下代码拒绝编译:

protocol MyProtocol {
func value<T>() -> T
}

class StringImpl: MyProtocol {
var string: String

init() {
self.string = "..."
}

init(string: String) {
self.string = string
}

func value<String>() -> String {
return self.string as! String
}
}

class BoolImpl: MyProtocol {
var value: Bool

init() {
self.value = false
}

init(value: Bool) {
self.value = value
}

func value<Bool>() -> Bool {
return self.value as! Bool
}
}

特别错误

error: invalid redeclaration of 'value()'
func value<Bool>() -> Bool {

这可能意味着我不能有不同的协议(protocol)泛型方法实现,但我没有看到明确的原因。

(我不是说强制类型转换为通用类型阴影现有类型)

附言对于那些好奇的人,我可能会告诉你,我正在尝试制定不与关联类型混淆并且在某种程度上仍然是通用的协议(protocol)。

最佳答案

你没问题,错误是var value , 并重新声明一个名称为 func value<Bool> 的函数,我只是更改了变量名并且它起作用了,错误清楚地说

error: invalid redeclaration of 'value()'

class BoolImpl: MyProtocol {
var bool: Bool

init() {
self.bool = false
}

init(value: Bool) {
self.bool = value
}

func value<Bool>() -> Bool {
return self.bool as! Bool
}
}

关于具有泛型方法的 Swift 协议(protocol) : invalid redeclaration of implementation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55196988/

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