@@ -4,44 +4,56 @@ import Foundation
44/// This gives guarantees on non-destructive iteration, and offers an indexed
55/// ordering to the key-value pairs in the document.
66extension Document : Collection {
7+ /// The index type of a document.
8+ public typealias Index = Int
9+
710 /// Returns the start index of the Document.
8- public var startIndex : Int {
11+ public var startIndex : Index {
912 return 0
1013 }
1114
1215 /// Returns the end index of the Document.
13- public var endIndex : Int {
16+ public var endIndex : Index {
1417 return self . count
1518 }
1619
17- private func failIndexCheck( _ i: Int ) {
20+ private func failIndexCheck( _ i: Index ) {
1821 let invalidIndexMsg = " Index \( i) is invalid "
1922 guard !self . isEmpty && self . startIndex ... self . endIndex - 1 ~= i else {
2023 fatalError ( invalidIndexMsg)
2124 }
2225 }
2326
2427 /// Returns the index after the given index for this Document.
25- public func index( after i: Int ) -> Int {
28+ public func index( after i: Index ) -> Index {
2629 // Index must be a valid one, meaning it must exist somewhere in self.keys.
2730 failIndexCheck ( i)
2831 return i + 1
2932 }
3033
3134 /// Allows access to a `KeyValuePair` from the `Document`, given the position of the desired `KeyValuePair` held
3235 /// within. This method does not guarantee constant-time (O(1)) access.
33- public subscript( position: Int ) -> KeyValuePair {
36+ public subscript( position: Index ) -> KeyValuePair {
3437 // TODO: This method _should_ guarantee constant-time O(1) access, and it is possible to make it do so. This
3538 // criticism also applies to key-based subscripting via `String`.
3639 // See SWIFT-250.
3740 failIndexCheck ( position)
38- // swiftlint:disable:next force_unwrapping - failIndexCheck precondition ensures non-nil result.
39- return DocumentIterator . subsequence ( of: self , startIndex: position, endIndex: position + 1 ) . first!
41+ guard let iter = DocumentIterator ( forDocument: self ) else {
42+ fatalError ( " Failed to initialize an iterator over document \( self ) " )
43+ }
44+
45+ for pos in 0 ... position {
46+ guard iter. advance ( ) else {
47+ fatalError ( " Failed to advance iterator to position \( pos) " )
48+ }
49+ }
50+
51+ return ( iter. currentKey, iter. currentValue)
4052 }
4153
4254 /// Allows access to a `KeyValuePair` from the `Document`, given a range of indices of the desired `KeyValuePair`'s
4355 /// held within. This method does not guarantee constant-time (O(1)) access.
44- public subscript( bounds: Range < Int > ) -> Document {
56+ public subscript( bounds: Range < Index > ) -> Document {
4557 // TODO: SWIFT-252 should provide a more efficient implementation for this.
4658 return DocumentIterator . subsequence ( of: self , startIndex: bounds. lowerBound, endIndex: bounds. upperBound)
4759 }
0 commit comments