wickwirew / Runtime

A Swift Runtime library for viewing type info, and the dynamic getting and setting of properties.
MIT License
1.08k stars 94 forks source link

Getting array<T> where T would be a specific type? #83

Closed LittleCodingFox closed 3 years ago

LittleCodingFox commented 3 years ago

Hello, Is there a way to create an empty array with a generic type T where T would be obtained from type(of: something else)?

So I'd like to do something like:

let type = type(of: X)
let arrayType = <...>
let arrayTypeInfo = try typeInfo(of: arrayType)

var array = arrayTypeInfo.createInstance()

Thank you for your help!

wickwirew commented 3 years ago

Not nicely. You could always create a protocol that has a static extension that returns Self wrapped as an array and manually conform a bunch of types to it. If that's not what your looking for, and you want a more runtime hacky solution that works for everything it could be similar but we could force cast the type to the protocol.

struct ProtocolTypeContainer {
    let type: Any.Type
    let witnessTable: Int
}

protocol Arrayable {}
extension Arrayable {
    static func arrayType() -> Any.Type {
        return [Self].self
    }
}

func arrayType(wrapping type: Any.Type) -> Any.Type {
    let container = ProtocolTypeContainer(type: type, witnessTable: 0)
    let arrayable = unsafeBitCast(container, to: Arrayable.Type.self)
    return arrayable.arrayType()
}

let myValue: Any = 0

print(arrayType(wrapping: Int.self)) // Array<Int>
print(arrayType(wrapping: String.self)) // Array<String>
print(arrayType(wrapping: type(of: myValue))) // Array<Int>