【问题标题】:In Swift, How do I use an associatedtype in a Generic Class where the type parameter is constrained by the protocol?在 Swift 中,如何在类型参数受协议约束的泛型类中使用关联类型?
【发布时间】:2017-06-23 06:38:07
【问题描述】:

在 Swift 中,我有一个这样的协议:

protocol P {
    associatedtype T
    func f(val:T)
}

我想定义一个这样的类:

class B<X:P> {
}

然后在 B 类中使用associatedtypeT。

我试过了:

class B<X:P> {
    var v:T // compiler says "Use of undeclared type"

    init() {
    }
}

我也试过这个:

class B<X:P, Y> {
    typealias T = Y
    var v:T

    init() {
    }

    func g(val:X) {
        val.f(val: v) // compiler says "Cannot invoke 'f' with an argument list of type '(val:Y)'
    }
}

有什么建议吗?

【问题讨论】:

    标签: swift generics protocols


    【解决方案1】:

    T 是占位符类型X 的关联类型,因此您将其引用为X.T。示例:

    class B<X: P> {
        var v: X.T
    
        init(v: X.T) {
            self.v = v
        }
    
        func g(x: X) {
            x.f(val: v)
        }
    }
    

    【讨论】:

    • 谢谢!明白了!
    猜你喜欢
    • 1970-01-01
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多