public class Container2: RandomAccessCollection
{
public typealias Indices = DefaultRandomAccessIndices<Container2>;
public typealias Index = Int;
//typealias SubSequence = Container2;
public var arr:[Int] = [1,2,3,4,5];
public var endIndex: Index {
return 5;
}
public var startIndex:Index{
return 0;
}
public func index(after i: Int) -> Int{
return i+1;
}
public subscript(position: Int) -> Int{
get{
return arr[position];
} set{
arr[position] = newValue;
}
}
/*func index(before i: Int) -> Int{
return i-1;
}*/
public subscript(bounds: Range<Int>) -> Container2{
get{
return Container2();
} set{
}
}
}
I'm trying to adopt the RandomAccessCollection protocol from a class. I deliberately leave out the func index(before:) function because there is already a default implementation of that function in RandomAccessCollection. I do understand that that function's implementation is required because of BiDirectionalCollection from which RandomAccessCollection inherits.
My question is why would the compiler complain that func index(before:) implementation is required when there is already a default implementation in RandomAccessCollection that i can use?
Thanks.
ole
(Ole Begemann)
2
The default implementation for index(before:) is in an extension with these constraints:
extension RandomAccessCollection where Index : Strideable,
Index.Stride == IndexDistance,
Indices == CountableRange<Index> {
...
public func index(before i: Self.Index) -> Self.Index
...
}
Your collection type doesn't satify these constraints because Container2.Indices is DefaultRandomAccessIndices. If you replace the typealias with:
typealias Indices = CountableRange<Int>
it will work.
···
On 12/03/2017 16:58, Don Giovanni via swift-users wrote:
I'm trying to adopt the RandomAccessCollection protocol from a class. I
deliberately leave out the func index(before:) function because there
is already a default implementation of that function in
RandomAccessCollection. I do understand that that function's
implementation is required because of BiDirectionalCollection from which
RandomAccessCollection inherits.
My question is why would the compiler complain that func index(before:)
implementation is required when there is already a default
implementation in RandomAccessCollection that i can use?