I'm using this extension to safely index into an array, which has worked well, but now and then I am seeing a crash on this line guard let priorSamplesEndDate = currentSamplesInShiftInterval[safe: indexOfCurrentSample - 1]?.endDate else { return }
and cannot figure out how this could ever be out of range?
//Safe Indexing Extension
extension Collection where Indices.Iterator.Element == Index {
public subscript(safe index: Index) -> Iterator.Element? {
return (startIndex <= index && index < endIndex) ? self[index] : nil
}
}
//usage
if currentSamplesInShiftInterval.count > 1 {
guard let indexOfCurrentSample = currentSamplesInShiftInterval.firstIndex(of: distanceSample) else {return }
guard let priorSamplesEndDate = currentSamplesInShiftInterval[safe: indexOfCurrentSample - 1]?.endDate else { return } //crash occurs here for index out of range
}