[swift-evolution] [Pitch] Adding safety to arrays

David Sweeris davesweeris at mac.com
Thu Apr 13 09:54:11 CDT 2017




Sent from my iPhone
> On Apr 13, 2017, at 07:34, Jeff Kelley <slaunchaman at gmail.com> wrote:
> 
> Apologies if this has been suggested before, but going off of Andrew’s message, a simple syntax could be to use our existing Optional syntax:
> 
> let array = ["foo", "bar", "baz"]
> 
> let first = array[0] // type is `String`
> let third = array[2?] // type is `String?`, value is .some("baz")
> let fourth = array[3?] // type is `String?`, value is .none

That was my thought, too, but it's not valid Swift. I tried it in a playground before I sent my reply. At least in Xcode 8.3.1, it gives an error about ambiguous calls (it can't decide if you're trying to call the stdlib subscript or the `(_: Index?) -> Element?` one from the extension), and if you fix that by adding an argument label, the real issue is revealed which is that saying "x?" doesn't return "x wrapped in an optional"; it thinks you're trying to do Optional chaining on a non-optional value, which isn't allowed.

I wouldn't object to adding that "trailing '?' wraps the value" behavior (or maybe "¿", since they really would have the opposite result), in which case this should work fine (although the choice of argument label, or lack thereof, will likely still be bikeshedded)

Anyway, unless someone who knows more about this than I do (probably most of you) says this functionality is a Bad Idea (™), I'm in favor of it.

- Dave Sweeris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170413/77a20e59/attachment.html>


More information about the swift-evolution mailing list