10
10
11
11
/// An ordered set is an ordered collection of instances of `Element` in which
12
12
/// uniqueness of the objects is guaranteed.
13
- public struct OrderedSet < E: Hashable > : Equatable , Collection {
13
+ public struct OrderedSet < E: Hashable > : Equatable , MutableCollection , RandomAccessCollection {
14
14
public typealias Element = E
15
15
public typealias Index = Int
16
16
public typealias Indices = CountableRange < Int >
@@ -77,6 +77,39 @@ public struct OrderedSet<E: Hashable>: Equatable, Collection {
77
77
array. removeAll ( keepingCapacity: keepCapacity)
78
78
set. removeAll ( keepingCapacity: keepCapacity)
79
79
}
80
+
81
+ // MARK:- MutableCollection, RandomAccessCollection conformance
82
+
83
+ public var startIndex : Int { return contents. startIndex }
84
+ public var endIndex : Int { return contents. endIndex }
85
+
86
+ public subscript( position: Int ) -> Element {
87
+ get {
88
+ return array [ position]
89
+ }
90
+ set ( newValue) {
91
+ let oldValue = array [ position]
92
+ // Remove the old value from set.
93
+ set. remove ( oldValue)
94
+ // Add the new value.
95
+ array [ position] = newValue
96
+ set. insert ( newValue)
97
+ }
98
+ }
99
+
100
+ public subscript( bounds: Range < Int > ) -> ArraySlice < Element > {
101
+ get {
102
+ return array [ bounds]
103
+ }
104
+ set ( newValues) {
105
+ let oldValues = array [ bounds]
106
+ // Remove the old values from set.
107
+ oldValues. forEach { set. remove ( $0) }
108
+ // Add the new values.
109
+ array [ bounds] = newValues
110
+ newValues. forEach { set. insert ( $0) }
111
+ }
112
+ }
80
113
}
81
114
82
115
extension OrderedSet : ExpressibleByArrayLiteral {
@@ -89,14 +122,6 @@ extension OrderedSet: ExpressibleByArrayLiteral {
89
122
}
90
123
}
91
124
92
- extension OrderedSet : RandomAccessCollection {
93
- public var startIndex : Int { return contents. startIndex }
94
- public var endIndex : Int { return contents. endIndex }
95
- public subscript( i: Int ) -> Element {
96
- return contents [ i]
97
- }
98
- }
99
-
100
125
public func == < T> ( lhs: OrderedSet < T > , rhs: OrderedSet < T > ) -> Bool {
101
126
return lhs. contents == rhs. contents
102
127
}
0 commit comments