Test if Any parameter is an Array of another Any

given inputs

func isElementType(element:Any, array:Any) -> Bool

how can i make this return true if and only if the concrete type of array is an Array of the concrete type of element?

isElementType(element: 1 as Int, array: [] as [Int])          == true
isElementType(element: 1 as Float, array: [] as [Float])      == true
isElementType(element: [] as [Float], array: [] as [[Float]]) == true

If you know that array isn't empty, the following works.

func isElementType(element: Any, array: Any) -> Bool {
    return type(of: Mirror(reflecting: array).children.first!.value) == type(of: element)
}

I'd try something like:

protocol ElementTypeCheckable {
    func isElementType(_ element: Any) -> Bool
}

extension Array : ElementTypeCheckable {
    func isElementType(_ element: Any) -> Bool {
        return element is Element
    }
}

func isElementType(element: Any, array: Any) -> Bool {
    return (array as? ElementTypeCheckable)?.isElementType(element) ?? false
}
2 Likes