[swift-evolution] Proposal: Allow explicit type parameter specification in generic function call

Brent Royal-Gordon brent at architechies.com
Sun Dec 4 04:56:19 CST 2016


> On Dec 1, 2016, at 2:09 PM, Dave Abrahams via swift-evolution <swift-evolution at swift.org> wrote:
> 
> More
> importantly, they suggest that the metatype argument will be used in
> some dynamic way (e.g. by calling a static method or an init), instead
> of just as a way to get the right type inference.  In some cases that
> can make a dramatic difference in the resulting semantics.
> 
>    func polymorphicSomething<T>(_: T.Type) {
>      ...
>    }
> 
>    class Base {}
>    class Derived : Base {}
> 
>    func otherThing(x: Base) {
>      // Surprise! I'm going to ignore the dynamic type you gave me and
>      // just use Base
>      polymorphicSomething(type(of: y)) 
>    }
> 
>    otherThing(Derived())

For what it's worth, I believe the pull request Anton mentioned above (<https://github.com/apple/swift-evolution/pull/553>) addresses this. It provides both `Type<T>`, which means *exactly* T, and `AnyType<T>`, which means *any subtype of* `T`. You'd use `Type<T>` for type-pinning parameters and `AnyType<T>` for dynamically-typed parameters.

(`AnyType<T>` is a protocol-like type which all `Type<_>`s for subtypes of `T` "conform" to. Thus, you can pass a `Type<T>` as an `AnyType<T>`, but not vice versa.)

In other words, if `polymorphicSomething` were declared like:

   func polymorphicSomething<T>(_: AnyType<T>) {
     ...
   }

Then you would expect it to use the specific subtype you provided. But if you said:

   func polymorphicSomething<T>(_: Type<T>) {
     ...
   }

Then it would be clear in the signature that it was using only the static type of `T`, not the dynamic type. (It'd be clear because `Type<T>` can only contain `T`'s type instance, not subtypes' type instances.) Since `type(of:)` would return an `AnyType<Base>`, this line:

     polymorphicSomething(type(of: y))

Would be trying to pass `AnyType<Base>` to a `Type<_>` parameter, which would not fly. Thus, it would fail at compile time.

-- 
Brent Royal-Gordon
Architechies



More information about the swift-evolution mailing list