Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active March 19, 2017 12:27
Show Gist options
  • Save KentarouKanno/6f3d0ef3b81d8543ab36bcc24107e121 to your computer and use it in GitHub Desktop.
Save KentarouKanno/6f3d0ef3b81d8543ab36bcc24107e121 to your computer and use it in GitHub Desktop.

Collection + extension

★ 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
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment