[swift-evolution] [Discussion] Seal `T.Type` into `Type<T>`

Anton Zhilin antonyzhilin at gmail.com
Fri Jul 15 12:05:52 CDT 2016


You’ve got two things wrong there:

   1. Derived: Base otherwise you cannot cast at all.
   2. w === x //=> FALSE

The reason why this does not work is because it’s impossible to cast a type
to an different type with the help of an initializer. As I cleaned up the
current implementation I though about replacing init?(casting: Type<T>?)
with something like this:

public static func cast<U>(from optionalType: Type<U>?) -> Type<T>? {

    guard let otherType = optionalType else { return nil }

    // Check if we can up- or downcast the metatype from `otherType`
to `Metatype<T>`

    // Bug: SR-2085
    // Workaround: Check explicitly if `T` is `Any`
    //
    // let isTAny = _uniqueIdentifierOf(Any.metatype) ==
_uniqueIdentifierOf(T.metatype)
    // guard isTAny || otherType._metatype is Metatype<T> else {
    //      return nil
    // }

    guard otherType._metatype is Metatype<T> else {
        return nil
    }
    // `T` implicitly converted to `Type<T>()`
    return unsafeBitCast(otherType, to: T)
}

Brilliant! But I disagree with from label. “Cast from type” means that we
somehow use Type<U> statically. But we need to cast optionalType itself to
Type<T>. I suggest to use cast(_:) signature.

Next, I’d like to remind you of my size, stride, align concerns. Consider
this example:

let x = Type<Int>()let y = Type<CustomStringConvertible>(casting: x)!
x.size  //=> 8
y.size  //=> 8 or 40?

I think that y.size should be 8, because we are dynamically checking size
of particular instance y, which refers to specific subtype of
CustomStringConvertible. We should look into corresponding witness table or
whatever, and get the size at runtime. In the future, when we add more
reflection features, they will also collect information about particular
type instances.
​
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160715/7efc1ff0/attachment.html>


More information about the swift-evolution mailing list