[swift-evolution] Optional safe subscripting for arrays

Maximilian Hünenberger m.huenenberger at me.com
Sat Jan 16 16:08:46 CST 2016


I've also thought of this. But the concept of safe indexing can also be extended to CollectionType (or to the more abstract Indexable protocol) where it's index is Comparable.

For mutable Collections/MutableIndexable there could be two versions of a safe subscript set:

array[safe: 5] = 7 // does nothing if index out of bounds

array[clamp: 5] = 7
// if array is empty: does nothing
// if 5 >= array.endIndex : sets last element
// if index < 0 : sets first index

So definitely worth considering.


- Maximilian

> Am 16.01.2016 um 21:44 schrieb Rudolf Adamkovič via swift-evolution <swift-evolution at swift.org>:
> 
> Hi there!
> 
> From time to time, I find myself using safe subscripting, e.g.:
> 
> let array = [1, 2, 3]
> 
> array[safe: 0] // 1
> array[safe: 1] // 2
> array[safe: 2] // 3
> array[safe: 3] // nil
> 
> … with the following implementation:
> 
> subscript (safe index: Int) -> Element? {
>     return self.indices ~= index ? self[index] : nil
> }
> 
> I was wondering … wouldn’t it be handy to have this in the standard library?
> 
> Best regards,
> Rudolf Adamkovic
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160116/a5e2b204/attachment.html>


More information about the swift-evolution mailing list