Last active
February 6, 2019 20:02
-
-
Save AmitaiB/7a7796df09ef8f30b09db9b0b4728bca to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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