Swift: how to get the type of an array element having an available MirrorType array

Suppose I have an MirrorType

array.

I need to get the element type of this array type and then create a new element of that type.

eg.

let elementType : Any.Type = some_magic_function(arrayMirrorType)
var arrayElement = some_magic_element_constructor(elementType)

      

I thought it might be possible to drop arrayMirrorType.valueType

before Array<Any>.Type

for example.

let arrayType = arrayMirrorType.valueType as! Array<Any>.Type
let elementType = arrayType.Generator.Element

      

But the casting does not Array<Any>.Type

approve.

+3


source to share


1 answer


Array<Any>.Type

is not a subtype Array<String>.Type

, so the result nil

and you get a validation assertion.

What you can do here is iterate through the reflection of the array and query for the type of each item.

let arrayMirrorType = reflect(array)

      



...

for var i = 0; i<arrayMirrorType.count; i++ {
    let elementType = arrayMirrorType[i].1.valueType

    if let intElementType = elementType as? Int.Type {
        let newElement = intElementType(777)
    }
}

      

+2


source







All Articles