The error I get is unsurprising, but how would I accomplish something like this in Swift?
let stringType = String.self
let stringArrayType = Array<String>.self
let stringArrayTypeFromVariable = Array<stringType>.self // Error :Use of undeclared type 'stringType'
My final goal is to build a function like this.
print( getTypeAsArray( Int.self ) ) // prints "Array<Int>.Type"
print( getTypeAsArray( String.self ) ) // prints "Array<String>.Type"
Here's my current attempt. It doesn't compile, but I think maybe this is solvable with generics like this.
// this version doesn't compile...
func getTypeAsArray<T>(_ value: T) -> [T].Type {
return []
}
getTypeAsArray(String.self)
// this version compiles, but doesn't give me the functionality I want...The expected output was Array<String>, not Array<String.Type>
func getTypeAsArray<T>(_ value: T) -> [T].Type {
return type(of: [])
}
getTypeAsArray(String.self) // -> Array<String.Type>
getTypeAsArray?Any.Typeparameter, right? What type would it return?tof typeAny.Type. This is so that at runtime,tcould store any meta type object. But what would the method return? It can't return[Any].Type, because metatypes are not covariant.getTypeAsArray. You probably meantfunc getTypeAsArray<T>(_ value: T.Type) -> [T].Type { return [T].self }.