Skip to content

Instantly share code, notes, and snippets.

@AmitaiB
Last active February 6, 2019 20:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AmitaiB/7a7796df09ef8f30b09db9b0b4728bca to your computer and use it in GitHub Desktop.
Save AmitaiB/7a7796df09ef8f30b09db9b0b4728bca to your computer and use it in GitHub Desktop.
// Not mine, forgot to whom to give the credit. :(
import Foundation
/// Allows `collection.safe.whatever`. Mimics usage of AVFoundation's `collection.lazy.whatever`
public struct SafeCollection<Base : Collection> {
private var _base: Base
public init(_ base: Base) {
_base = base
}
private func distance(from startIndex: Base.Index) -> Int {
return _base.distance(from: startIndex, to: _base.endIndex)
}
private func distance(to endIndex: Base.Index) -> Int {
return _base.distance(from: _base.startIndex, to: endIndex)
}
public subscript(index: Base.Index) -> Base.Iterator.Element? {
if distance(to: index) >= 0 && distance(from: index) > 0 {
return _base[index]
}
return nil
}
public subscript(bounds: Range<Base.Index>) -> Base.SubSequence? {
if distance(to: bounds.lowerBound) >= 0 && distance(from: bounds.upperBound) >= 0 {
return _base[bounds]
}
return nil
}
public subscript(bounds: ClosedRange<Base.Index>) -> Base.SubSequence? {
if distance(to: bounds.lowerBound) >= 0 && distance(from: bounds.upperBound) > 0 {
return _base[bounds]
}
return nil
}
}
public extension Collection {
var safe: SafeCollection<Self> {
return SafeCollection(self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment