Files
Brandon Williams 662fee0304 Restrict Shared.elements to IdentifiedArray only. (#3187)
* Restrict Shared.elements to IdentifiedArray only.

* wip

* wip

* wip

* fix test

---------

Co-authored-by: Stephen Celis <stephen@stephencelis.com>
2024-06-19 12:26:55 -07:00

49 lines
1.2 KiB
Swift

final class DefaultSubscript<Value>: Hashable {
var value: Value
init(_ value: Value) {
self.value = value
}
static func == (lhs: DefaultSubscript, rhs: DefaultSubscript) -> Bool {
lhs === rhs
}
func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(self))
}
}
extension Optional {
subscript(default defaultSubscript: DefaultSubscript<Wrapped>) -> Wrapped {
get { self ?? defaultSubscript.value }
set {
defaultSubscript.value = newValue
if self != nil { self = newValue }
}
}
}
extension RandomAccessCollection where Self: MutableCollection {
subscript(
position: Index,
default defaultSubscript: DefaultSubscript<Element>
) -> Element {
get { self.indices.contains(position) ? self[position] : defaultSubscript.value }
set {
defaultSubscript.value = newValue
if self.indices.contains(position) { self[position] = newValue }
}
}
}
extension _MutableIdentifiedCollection {
subscript(
id id: ID,
default defaultSubscript: DefaultSubscript<Element>
) -> Element {
get { self[id: id] ?? defaultSubscript.value }
set {
defaultSubscript.value = newValue
self[id: id] = newValue
}
}
}