|
| 1 | +public struct SafeCollection<C>: Collection where C: Collection { |
| 2 | + public typealias Index = C.Index |
| 3 | + public typealias Element = Optional<C.Element> |
| 4 | + |
| 5 | + private var collection: C |
| 6 | + |
| 7 | + init(_ collection: C) { |
| 8 | + self.collection = collection |
| 9 | + } |
| 10 | + |
| 11 | + public subscript(position: Index) -> Element { |
| 12 | + guard self.collection.indices.contains(position) else { return nil } |
| 13 | + return self.collection[position] |
| 14 | + } |
| 15 | + |
| 16 | + public var startIndex: Index { |
| 17 | + return self.collection.startIndex |
| 18 | + } |
| 19 | + |
| 20 | + public var endIndex: Index { |
| 21 | + return self.collection.endIndex |
| 22 | + } |
| 23 | + |
| 24 | + public func index(after i: Index) -> Index { |
| 25 | + return self.collection.index(after: i) |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +public struct SafeMutableCollection<C>: MutableCollection where C: MutableCollection { |
| 30 | + public typealias Index = C.Index |
| 31 | + public typealias Element = Optional<C.Element> |
| 32 | + |
| 33 | + fileprivate var collection: C |
| 34 | + |
| 35 | + init(_ collection: C) { |
| 36 | + self.collection = collection |
| 37 | + } |
| 38 | + |
| 39 | + public subscript(position: Index) -> Element { |
| 40 | + get { |
| 41 | + guard self.collection.indices.contains(position) else { return nil } |
| 42 | + return self.collection[position] |
| 43 | + } |
| 44 | + set { |
| 45 | + guard let value = newValue else { return } |
| 46 | + guard self.collection.indices.contains(position) else { return } |
| 47 | + self.collection[position] = value |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + public var startIndex: Index { |
| 52 | + return self.collection.startIndex |
| 53 | + } |
| 54 | + |
| 55 | + public var endIndex: Index { |
| 56 | + return self.collection.endIndex |
| 57 | + } |
| 58 | + |
| 59 | + public func index(after i: Index) -> Index { |
| 60 | + return self.collection.index(after: i) |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +public extension Collection { |
| 65 | + public var safe: SafeCollection<Self> { |
| 66 | + return .init(self) |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +public extension MutableCollection { |
| 71 | + public var safe: SafeMutableCollection<Self> { |
| 72 | + get { return .init(self) } |
| 73 | + set { self = newValue.collection } |
| 74 | + } |
| 75 | +} |
0 commit comments