Use Swift `is` to check type of generic type

This is how to test a generic type parameter for conformance:

let conforms = T.self is MyProtocol.Type

See this post: Swift: check if generic type conforms to protocol


Here's 2 things that might work for you.

Option 1:

Note that child is a tuple containing a String? with the name of the property ("property" in your example) and the item. So you need to look at child.1.

In this case, you should be checking:

if String(describing: type(of: child.1)).hasPrefix("Foo<")

Option 2:

If you create a protocol FooProtocol that is implemented by Foo<T>, you could check if child.1 is FooProtocol:

protocol FooProtocol { }

struct Foo<T>: FooProtocol {}

struct Bar {
    var property = Foo<String>()
}

var test = Bar()

let mirror = Mirror(reflecting: test)

// This code is trying to count the number of properties of type Foo
var inputCount = 0
for child in mirror.children {
    if child.1 is FooProtocol {
        inputCount += 1
    }
}

Tags:

Generics

Swift