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

Adrian Zubarev adrian.zubarev at devandartist.com
Fri Jul 15 05:47:50 CDT 2016


Challenge accepted: Fixing your code to make it compile.

typealias SomeGeneric<T> = (T, Int)
func wrap<T>(_ value: T) -> SomeGeneric<T> {
    return (value, 42)
}

func recursivelyPrint<T>(_ value: T, depth: Int) {
    print(value)
    guard depth > 0 else { return }
    recursivelyPrint(wrap(value), depth: depth - 1)
}

recursivelyPrint(2.0, depth: 5)

//////////// Output
2.0
(2.0, 42)
((2.0, 42), 42)
(((2.0, 42), 42), 42)
((((2.0, 42), 42), 42), 42)
(((((2.0, 42), 42), 42), 42), 42)
Technically Type<T> should be able to reflect other Type<T>’s. There is nothing wrong about it.

let var1 = Int       // Type: Type<Int>
let var2 = Int()     // Type: Int
let var2 = Type<Int> // Type: Type<Type<Int>> where the metatype inside will be `Type<Int>.Type`
As you can see there won’t be any implicit infinite recursion.



-- 
Adrian Zubarev
Sent with Airmail

Am 15. Juli 2016 um 12:25:10, Adrian Zubarev (adrian.zubarev at devandartist.com) schrieb:

> I don't see any problems with Type<Type<T>>. There is finite number of types that are used in the program, and compiler can collect and store information about them all statically. Am I right?

Maybe not:

        func recursivelyPrint<T>(type: T.Type, depth: Int) {
                print(type)
                guard depth > 0 else { return }
                recursivelyPrint(type: type.dynamicType, depth: depth - 1)
        }
        recursivelyPrint(type: Int.self, depth: 5)

Great example. But we can adapt it to tuples or any generic type:

typealias SomeGeneric<T> = (T, Int)
func wrap<T>(_ value: T) -> SomeGeneric<T>

func recursivelyPrint<T>(_ value: T, depth: Int) {
    print(type)
    guard depth > 0 else { return }
    recursivelyPrint(wrap(value), depth: delth - 1)
}

Currently, such code does not compile, because compiler can't create any types dynamically, not only for SomeGeneric<T> = T.Type.
So this problem is not specific to Type<T>, and should not be solved separately.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160715/a413629e/attachment.html>


More information about the swift-evolution mailing list