Dear Erica: Extend Safe Index?

Dear Erica,

I’m trying to extend safe index to collection type instead of array. Can’t figure it out. Is this possible for collectionTypes in 2.0?

— Nathan Mann

Here’s my take. I’ve only given this the most minimal testing. Do please let me know how to improve on it!

// Thanks Jordan Rose for the IntegerType constraint
extension CollectionType where Index : IntegerType {
    subscript (safe index: UInt) ->
        Self.Generator.Element? {
        if Int(index) < numericCast(count) {
            return self[advance(startIndex,
                numericCast(index))]
        }
        return nil
    }
}
// Thanks Brent Royal-Gordon 
extension CollectionType where Index: Comparable {
    subscript (safe index: Index) -> Generator.Element? {
        guard startIndex <= index && index < endIndex else {
            return nil
        }
        return self[index]
    }
}

Comments are closed.