在Swift协议中为typealiases添加约束
发布时间:2020-12-14 04:26:44 所属栏目:百科 来源:网络整理
导读:我怎样才能指出B.Generator.Element应该是A? protocol SomeProtocol { typealias A typealias B: CollectionType func f(a: A) - B} 我意识到我可以做func f(node:B.Generator.Element) – B并完全消除A,但如果在某些其他协议中定义了A并且SomeProtocol继
我怎样才能指出B.Generator.Element应该是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: 编辑3: 解决方法
怎么样:
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) ... } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |