【发布时间】:2017-03-09 13:23:50
【问题描述】:
假设我有一个协议:
protocol Foo:Hashable, Comparable {}
还有一个将这个家伙作为泛型的结构:
struct UsingFoo<T:Foo> {}
到目前为止一切顺利。假设我想在第二个协议上使用Foo:
protocol Bar {
associatedtype FooType:Foo
func doSomething(with:UsingFoo<FooType>)
}
并在类上使用 Bar:
class UsingBar<F:Foo>:Bar {
typealias FooType = F
func doSomething(with: UsingFoo<F>) {}
}
现在说我想带这些人参加聚会:
class FooBarParty<F:Foo, B:Bar>: NSObject {
var b:B
init(b:B) {
self.b = b
// interestingly, this line below won't compile
// self.b = UsingBar<F>.init()
}
func thisWillCompile () {
UsingBar<F>.init().doSomething(with: UsingFoo<F>.init())
}
func thisWontCompile() {
b.doSomething(with: UsingFoo<F>.init())
}
func thisAlsoWont (anotherB:B) {
anotherB.doSomething(with: UsingFoo<F>.init())
}
}
编译器说:
Cannot convert value of type 'UsingFoo<F>' to expected argument type 'UsingFoo<_>'
问题是:我怎样才能使用Bar 类型的属性?一如既往,非常感谢任何评论
编辑:感谢接受的答案,我发现我应该指定FooType。它看起来像这样:
class FooBarParty<F:Foo, B:Bar> where B.FooType == F { ... }
【问题讨论】: