@@ -92,50 +92,48 @@ extension DictionaryOfDictionaries {
92
92
}
93
93
94
94
public subscript( key: Key ) -> Value ? {
95
- get { outerDict [ key. 0 ] ? [ key. 1 ] }
95
+ get { outerDict [ key. 0 ] ? [ key. 1 ] }
96
96
set {
97
- if let v = newValue { _ = updateValue ( v, forKey: key) }
98
- else { _ = removeValue ( forKey: key) }
97
+ if let v = newValue {
98
+ outerDict [ key. 0 , default: [ : ] ] [ key. 1 ] = v
99
+ } else {
100
+ // Remove the inner key from the inner dictionary.
101
+ outerDict [ key. 0 ] ? [ key. 1 ] = nil
102
+
103
+ // If that was the last entry in the inner dictionary,
104
+ // remove the entire inner entry.
105
+ if outerDict [ key. 0 ] ? . isEmpty == true {
106
+ outerDict [ key. 0 ] = nil
107
+ }
108
+ }
99
109
}
100
110
}
101
111
102
112
public subscript( key: OuterKey ) -> [ InnerKey : Value ] ? {
103
- get { outerDict [ key] }
113
+ get { outerDict [ key] }
104
114
set {
105
- if let v = newValue { _ = outerDict. updateValue ( v, forKey: key) }
106
- else { _ = outerDict. removeValue ( forKey: key) }
115
+ outerDict [ key] = newValue
107
116
}
108
117
}
109
118
}
110
119
111
120
// MARK: - mutating
112
121
extension DictionaryOfDictionaries {
113
- mutating func updateValue( _ v: Value , forKey keys : ( OuterKey , InnerKey )
122
+ mutating func updateValue( _ v: Value , forKey key : Key
114
123
) -> Value ? {
115
- if var innerDict = outerDict [ keys. 0 ] {
116
- let old = innerDict. updateValue ( v, forKey: keys. 1 )
117
- outerDict. updateValue ( innerDict, forKey: keys. 0 )
118
- return old
119
- }
120
- outerDict. updateValue ( [ keys. 1 : v] , forKey: keys. 0 )
121
- return nil
124
+ let old = self [ key]
125
+ self [ key] = v
126
+ return old
122
127
}
123
128
124
- mutating func removeValue( forKey keys : ( OuterKey , InnerKey )
129
+ mutating func removeValue( forKey key : Key
125
130
) -> Value ? {
126
- guard var innerDict = outerDict [ keys. 0 ]
127
- else { return nil }
128
- let old = innerDict. removeValue ( forKey: keys. 1 )
129
- if innerDict. isEmpty {
130
- outerDict. removeValue ( forKey: keys. 0 )
131
- }
132
- else {
133
- outerDict. updateValue ( innerDict, forKey: keys. 0 )
134
- }
131
+ let old = self [ key]
132
+ self [ key] = nil
135
133
return old
136
134
}
137
135
}
138
136
139
137
// MARK: - identity
140
138
141
- extension DictionaryOfDictionaries : Equatable where Value: Equatable { }
139
+ extension DictionaryOfDictionaries : Equatable where Value: Equatable { }
0 commit comments