[swift-evolution] Compiler Optimization of Optional-returning Functions followed by '!'

Russ Bishop xenadu at gmail.com
Fri Jan 20 00:41:03 CST 2017


> On Jan 19, 2017, at 4:17 PM, Xiaodi Wu via swift-evolution <swift-evolution at swift.org> wrote:
> 
> For those times when you _don't_ know how many elements there are, don't care, and for some reason can't be bothered to get `array.count`, but you need to explicitly access an element by its index *and* have a useful fallback value, IMO it's reasonable to have an alternative subscript like the proposed `array[lenient: 10]`. But with facilities like `for...in`, `map`, etc., and others like `count` and `enumerated`, it's hard to argue that it's nearly as common a scenario as those where you are given a known-good index.
> 

I’m not sure why people keep asking for this; the extension is trivial so anyone who wants it can have it:

extension Collection
{
    subscript(ifExists index: Index) -> Iterator.Element? {
        guard index < self.endIndex else { return nil }
        return self[index]
    }
}

// won't assert!
myArray[ifExists: 42]



Russ

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170119/e31c8c16/attachment.html>


More information about the swift-evolution mailing list