collection[safe: index]

// avoid index out-of-range
extension Collection { 
    /// return the element at the index if it is within range,
    /// otherwise nil.
    ///
    /// Example:
    /// `collection[safe: 20]`
    subscript(safe index: Index) -> Element? { 
        return indices.contains(index) ? self[index] : nil 
    } 
}

Last updated