【发布时间】:2016-04-18 10:39:54
【问题描述】:
不太清楚如何为那个起一个好的标题...
我想定义一个通用协议GBucket,它有点像一组相同类型的项目。有点像CollectionType,但功能要少得多。像这样:
public protocol GBucket {
associatedtype BElement
func splitBucket
<A: GBucket, B: GBucket where A.BElement == Self.BElement,
B.BElement == Self.BElement>
(idx: Int) -> ( A, B )
}
它本质上只是提供了一种将GBucket 拆分为两个新GBuckets 的方法。可以是符合协议的任何类型 - 即返回的部分不必是进行拆分的同一类。
我尝试将其作为示例实现:
extension ArraySlice : GBucket {
public typealias BElement = Generator.Element
public func splitBucket
<A: GBucket, B: GBucket where A.BElement == BElement,
B.BElement == BElement>
(idx: Int) -> ( A, B )
{
let ls : ArraySlice<A.BElement> = self[0..<idx]
let a : A = ls // this conversion FAILs
return ( a, self[idx..<self.count] ) // this too, of course ;-)
}
}
这会产生:
无法将'ArraySlice '类型的值转换为指定类型'A'
据我所知应该可以很好地转换。 ArraySlice 是 GBucket 并且元素类型是相同的,这要归功于 where 规范。
另一个更短的示例说明了不使用数组的问题:
public protocol GBucket {
associatedtype BElement
func otherBucket<A: GBucket where A.BElement == Self.BElement>() -> A
}
public class MyBucketType<T> : GBucket {
public typealias BElement = T
public func otherBucket<A: GBucket where A.BElement == BElement>() -> A {
return MyBucketType<A.BElement>()
}
}
我做错了什么?
【问题讨论】: