★ subscriptのアクセスで範囲外の場合はnilを返す
extension Collection where Indices.Iterator.Element == Index {
/// Returns the element at the specified index iff it is within bounds, otherwise nil.
subscript (safe index: Index) -> Generator.Element? {
return indices.contains(index) ? self[index] : nil
}
}
let array = [1, 2, 3, 4]
let index = array[safe: 2]
//=> 3
let nilIndex = array[safe: 5]
//=> nil
// ----------------------
extension Collection where Indices.Iterator.Element == Index {
/// Returns the element at the specified index iff it is within bounds, otherwise nil.
subscript (safe index: Index) -> Generator.Element? {
return startIndex <= index && index < endIndex ? self[index] : nil
}
}
// -----------------------
extension Collection where Indices.Iterator.Element == Index {
/// Returns the element at the specified index iff it is within bounds, otherwise nil.
subscript (safe index: Index) -> Generator.Element? {
return startIndex..<endIndex ~= index ? self[index] : nil
}
}