> On Dec 1, 2016, at 2:09 PM, Dave Abrahams via swift-evolution 
> <[email protected]> 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

_______________________________________________
swift-evolution mailing list
[email protected]
https://lists.swift.org/mailman/listinfo/swift-evolution

Reply via email to