File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 2020// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2121// SOFTWARE.
2222
23- public struct SafeIndex < T: Indexable > {
24- var index : T . Index
25- init ( _ index: T . Index ) {
23+ public struct SafeIndex < T: ForwardIndexType > {
24+ var index : T
25+ init ( _ index: T ) {
2626 self . index = index
2727 }
2828}
2929
3030prefix operator ^ { }
31- public prefix func ^ < T: Indexable > ( index: T . Index ) -> SafeIndex < T > {
31+ public prefix func ^ < T: ForwardIndexType > ( index: T ) -> SafeIndex < T > {
3232 return SafeIndex ( index)
3333}
3434
35- public extension Indexable {
36- public subscript( safe: SafeIndex < Self > ? ) -> Self . _Element ? {
37- guard let safe = safe else { return nil }
38- return ( self . startIndex..< self . endIndex) . contains ( safe. index) ? self [ safe. index] : nil
35+ public extension MutableIndexable {
36+ public subscript( safe: SafeIndex < Self . Index > ? ) -> Self . _Element ? {
37+ get {
38+ guard let safe = safe else { return nil }
39+ return ( self . startIndex..< self . endIndex) . contains ( safe. index) ? self [ safe. index] : nil
40+ }
41+
42+ set {
43+ guard let safe = safe, value = newValue where ( self . startIndex..< self . endIndex) . contains ( safe. index) else { return }
44+ self [ safe. index] = value
45+ }
3946 }
4047}
Original file line number Diff line number Diff line change @@ -31,5 +31,13 @@ class SafeIndexTests: XCTestCase {
3131 XCTAssertEqual ( arr [ ^1 ] , " B " )
3232 XCTAssertEqual ( arr [ ^2 ] , " C " )
3333 XCTAssertNil ( arr [ ^3 ] )
34+
35+ var mutableArr = [ " A " , " B " , " C " ]
36+ XCTAssertEqual ( mutableArr [ ^0 ] , " A " )
37+ XCTAssertEqual ( mutableArr [ ^1 ] , " B " )
38+ XCTAssertEqual ( mutableArr [ ^2 ] , " C " )
39+ XCTAssertNil ( mutableArr [ ^3 ] )
40+ mutableArr [ ^2 ] = " D "
41+ XCTAssertEqual ( mutableArr [ ^2 ] , " D " )
3442 }
3543}
You can’t perform that action at this time.
0 commit comments