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

标签 swift generics

我正在 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/

相关文章:

swift - #selector 未解析的标识符函数

reactjs - Typescript 中抽象泛型 Container 类子类的装饰器

vb.net - .NET 4 中是否允许泛型运算符重载?

ios - 正则表达式在 Swift 中查找和替换字符串开始和结束文本

ios - TableView 上的 Swift JSON 数据滞后

java - 如何指定泛型类?

java - 使用 List 参数实现泛型方法

Java反射-从非泛型类获取泛型方法

swift - 如何在 Swift 中创建直角 View ?

ios - 在 swift 3 中保存硬币变量