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

Dave Abrahams dabrahams at apple.com
Sun Dec 4 18:33:34 CST 2016


on Sun Dec 04 2016, Brent Royal-Gordon <brent-AT-architechies.com> wrote:

>> 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. 

I care about the use-site far more than the signature.  When you pass
something in angle brackets, the static type is very clearly what
matters.

-- 
-Dave


More information about the swift-evolution mailing list