Why can't I declare subscript<T> ?


(Jens Alfke) #1

Why can't a custom subscript operator be made generic? That is, Swift allows this inside a class/struct:
  func get<T>(key: String) -> T? { … }
but it doesn’t allow
  subscript<T>(key: String) -> T? { … } // syntax error at the “<"

This doesn’t make sense to me, since subscripts are just syntactic sugar; the subscript operator ought to support whatever a named function can support.

In this case I’m implementing a class that contains a JSON payload, and I want clients to be able to flexibly access properties of the JSON and assign them to values, with implicit type-casting, i.e.
  var name: String = revision[“name”] // invoke subscript with T=String
  var age: Int = revision[“age”] // invoke subscript with T=Int
(I got this idea from the Tailor library, although it doesn’t use subscripts, for reasons I now understand.)

—Jens

PS: I’m using Xcode 7.3; I believe that’s Swift 2.2?


(Trent Nadeau) #2

This is a known language limitation. See
https://bugs.swift.org/browse/SR-115. It looks like someone started to
implement it, but it has been dormant since December.

···

On Mon, Apr 11, 2016 at 5:04 PM, Jens Alfke via swift-users < swift-users@swift.org> wrote:

Why can't a custom subscript operator be made generic? That is, Swift
allows this inside a class/struct:
        func get<T>(key: String) -> T? { … }
but it doesn’t allow
        subscript<T>(key: String) -> T? { … } // syntax error at
the “<"

This doesn’t make sense to me, since subscripts are just syntactic sugar;
the subscript operator ought to support whatever a named function can
support.

In this case I’m implementing a class that contains a JSON payload, and I
want clients to be able to flexibly access properties of the JSON and
assign them to values, with implicit type-casting, i.e.
        var name: String = revision[“name”] // invoke subscript with
T=String
        var age: Int = revision[“age”] // invoke subscript with
T=Int
(I got this idea from the Tailor library, although it doesn’t use
subscripts, for reasons I now understand.)

—Jens

PS: I’m using Xcode 7.3; I believe that’s Swift 2.2?
_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users

--
Trent Nadeau


(Jens Alfke) #3

Thanks, good to know. The fork <https://github.com/stephencelis/swift/commits/generic-subscripts> with the implementation has been active more recently (Feb 29) but still looks incomplete.

—Jens

···

On Apr 11, 2016, at 2:08 PM, Trent Nadeau <tanadeau@gmail.com> wrote:

This is a known language limitation. See https://bugs.swift.org/browse/SR-115. It looks like someone started to implement it, but it has been dormant since December.