<div dir="ltr">This is a known language limitation. See <a href="https://bugs.swift.org/browse/SR-115" target="_blank">https://bugs.swift.org/browse/SR-115</a>. It looks like someone started to implement it, but it has been dormant since December.<div class="gmail_extra"><br><div class="gmail_quote">On Mon, Apr 11, 2016 at 5:04 PM, Jens Alfke via swift-users <span dir="ltr"><<a href="mailto:swift-users@swift.org" target="_blank">swift-users@swift.org</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">Why can't a custom subscript operator be made generic? That is, Swift allows this inside a class/struct:<br>
func get<T>(key: String) -> T? { … }<br>
but it doesn’t allow<br>
subscript<T>(key: String) -> T? { … } // syntax error at the “<"<br>
<br>
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.<br>
<br>
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.<br>
var name: String = revision[“name”] // invoke subscript with T=String<br>
var age: Int = revision[“age”] // invoke subscript with T=Int<br>
(I got this idea from the Tailor library, although it doesn’t use subscripts, for reasons I now understand.)<br>
<br>
—Jens<br>
<br>
PS: I’m using Xcode 7.3; I believe that’s Swift 2.2?<br>
_______________________________________________<br>
swift-users mailing list<br>
<a href="mailto:swift-users@swift.org" target="_blank">swift-users@swift.org</a><br>
<a href="https://lists.swift.org/mailman/listinfo/swift-users" rel="noreferrer" target="_blank">https://lists.swift.org/mailman/listinfo/swift-users</a><br>
</blockquote></div><br><br clear="all"><div><br></div>-- <br><div>Trent Nadeau</div>
</div></div>