Make it possible to have generic subscripts. Example:
extension Collection {
subscript<Indices: Sequence>(indices: Indices) -> [Iterator.Element] where Indices.Iterator.Element == Index {
// ...
}
Or a generic return type:
extension JSON {
subscript<T: JSONConvertible>(key: String) -> T?
}
Swift-evolution thread: Generic Subscripts.
Currently, subscripts can't be generic. This is limiting in a number of ways:
- Some subscripts are very specific and could be made more generics.
- Some generic methods would feel more natural as a subscript, but currently can't be. This also makes it impossible to use them as lvalues.
This feature is also mentioned in the generics manifesto under generic subscripts.
Add generics to subscripts. There are two pieces to this: where to add the generic parameter list, and where to add the where
-clause. The most straightforward way would be to use the same syntax as methods:
extension Dictionary {
subscript<Indices: Sequence>(indices: Indices) -> [Iterator.Element] where Indices.Iterator.Element == Index {
// ...
}
TBD
Currently, there is a JIRA bug and a branch with some initial work.
This is a purely additive change. We don't propose changing the Standard Library to use this new feature, that should be part of a separate proposal. (Likewise, we should consider making subscripts throws
in a separate proposal).
TODO
Does the proposal change the ABI of existing language features? The
ABI comprises all aspects of the code generation model and interaction
with the Swift runtime, including such things as calling conventions,
the layout of data types, and the behavior of dynamic features in the
language (reflection, dynamic dispatch, dynamic casting via as?
,
etc.). Purely syntactic changes rarely change existing ABI. Additive
features may extend the ABI but, unless they extend some fundamental
runtime behavior (such as the aforementioned dynamic features), they
won't change the existing ABI.
Features that don't change the existing ABI are considered out of scope for Swift 4 stage 1. However, additive features that would reshape the standard library in a way that changes its ABI, such as where clauses for associated types, can be in scope. If this proposal could be used to improve the standard library in ways that would affect its ABI, describe them here.
TODO
API resilience describes the changes one can make to a public API without breaking its ABI. Does this proposal introduce features that would become part of a public API? If so, what kinds of changes can be made without breaking ABI? Can this feature be added/removed without breaking ABI? For more information about the resilience model, see the library evolution document in the Swift repository.
None.