[swift-evolution] [Pitch] Named subscripts

Dave Abrahams dabrahams at apple.com
Thu Nov 17 16:27:38 CST 2016


on Thu Nov 17 2016, Adrian Zubarev <swift-evolution at swift.org> wrote:

> Dear Swift community,
>
> while building a framework for BSON I had the following idea.
>
> Here is a snippet of some code I do have in my module:
>
> extension Array where Element == Document.Value {
>
>     public func double(at index: Int) -> Double? {
>
>         guard self.startIndex <= index && index < self.endIndex else { return nil }
>
>         if case .double(let double) = self[index] {
>
>             return double
>         }
>         return nil
>     }
>
>> }
> This function is used to query the array and check if the element at the given index is of a
> specific type. Now I would like also to implement a semi-schema setter.
>
> The problem that I see, is the ugliness of the subscript I’d create.
>
> Currently the code would read nicely let d = array.double(at: 42), but after change to a subscript
> the API would look odd array[doubleAt: 42] = 5.0.
>
> Don’t get me wrong here, I also have methods with larger names like public func scopedJavaScript(at
> index: Int) -> …. You can easily imagine that such subscripts would look ugly
> array[scopedJavaScriptAt: 123] = ….
>
> I propose to align the design of subscript with functions where one could optionally give subscript
> a name.
>
> func name(label parameter: Type) -> ReturnType
>
> subscript optionalName(label parameter: Type) -> ReturnType
> This change would make my API nice and
> clean. array.scopedJavaScript[at: 213] = …

You do that by giving your Array a scopedJavaScript property, and
making that indexable.

-- 
-Dave



More information about the swift-evolution mailing list