Array.subscript(safe:) -> T?

Originator:robnapier
Number:rdar://21403129 Date Originated:16-Jun-2015 12:23 PM
Status:Open Resolved:
Product:Developer Tools Product Version:Swift 2b1
Classification:Enhancement Reproducible:Always
 
Array should offer a “safe” version of subscript.

// Thanks Mike Ash
extension Array {
    subscript (safe index: Int) -> Element? {
        return Int(index) < count ? self[Int(index)] : nil
    }
}

Comments

Nice. However, array[safe: -1] will fail. Checking for indices.contains(index) will be safer.


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!