我怎样才能指出B.Generator.Element应该是A? protocol SomeProtocol { typealias A typealias B: CollectionType func f(a: A) - B} 我意识到我可以做func f(node:B.Generator.Element) – B并完全消除A,但如果在某些其他协
protocol SomeProtocol {
typealias A
typealias B: CollectionType
func f(a: A) -> B
}
我意识到我可以做func f(node:B.Generator.Element) – > B并完全消除A,但如果在某些其他协议中定义了A并且SomeProtocol继承了它,我就不能这样做.
编辑:
添加了示例
protocol P {
typealias A
}
protocol Q: P {
typealias B: CollectionType
typealias A = B.Generator.Element
func f(node: A) -> B
}
func g<A, T: Q where A == T.A>(arg1: T, arg2: A) {
let collection = arg1.f(arg2)
collection.contains(arg2) // Error here
}
编辑2:
为了澄清,我希望以某种方式在协议本身中指定A == B.Generator.Element,因为我必须使用自由函数.我在开发者论坛中找到了一个thread,正是我的问题.看起来它是当前类型系统的一个限制.我已经提交了一个雷达,让我们希望它得到解决:)
编辑3:
该问题已经存在雷达.提交时使用rdar:// 21420236.
protocol SomeProtocol {
typealias A = B.Generator.Element
typealias B: CollectionType
func f(a: A) -> B
}
编辑:
您得到的错误是因为无法保证A(B.Generator.Element)符合Equatable.因此,您无法在集合上调用contains,因为contains定义为:
extension SequenceType where Generator.Element : Equatable {
public func contains(element: Self.Generator.Element) -> Bool
}
(我不确定为什么Xcode会提供包含作为一种有效的方法来调用,可能是一个错误……)
要解决这个问题,您可以:
// Since you're using Swift 2 you could use a protocol extension instead of a free function.
// Unfortunately, Xcode complains without the explicit declaration that `A` is
// `B.Generator.Element`.
extension Q where A: Equatable, A == B.Generator.Element {
func g(elem: A) {
let collection = f(elem)
collection.contains(elem)
...
}
}
