使用Swift`is`检查泛型类型

Tre*_*vör 8 generics swift

可以说我有一个类型为type的变量Any,我想知道这是否是数组,这是我想做的:

if myVariable is Array { /* Do what I want */ }
Run Code Online (Sandbox Code Playgroud)

但是Swift需要提供数组的通用类型,例如:

if myVariable is Array<Int> { }
Run Code Online (Sandbox Code Playgroud)

但是我不想检查泛型类型,我只是想知道这是否是数组,我试过了:

if myVariable is Array<Any> { }  
Run Code Online (Sandbox Code Playgroud)

希望它可以匹配每种类型的数组,但是也不起作用...(它不匹配所有类型的数组,因此,如果我的变量是一个Int数组,则不会调用此代码)

我该怎么办 ?

谢谢。

使用似乎无效的方法解决方案示例进行编辑:

struct Foo<T> {}

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 {
    print(String(describing: type(of: child))) // Prints "(Optional<String>, Any)"
    if String(describing: type(of: child)) == "Foo" {
        inputCount += 1 // Never called
    }
}

print(inputCount) // "0"
Run Code Online (Sandbox Code Playgroud)

Les*_*win 7

这是测试泛型类型参数一致性的方法:

let conforms = T.self is MyProtocol.Type
Run Code Online (Sandbox Code Playgroud)

请参阅这篇文章:Swift:检查泛型类型是否符合协议


vac*_*ama 6

这里有两件事可能对你有用。

选项1:

请注意,这child是一个包含String?属性名称("property"在您的示例中)和项目的元组。所以你需要看看child.1

在这种情况下,您应该检查:

if String(describing: type(of: child.1)).hasPrefix("Foo<")
Run Code Online (Sandbox Code Playgroud)

选项 2:

如果您创建一个FooProtocol由 实现的协议Foo<T>,您可以检查是否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
    }
}
Run Code Online (Sandbox Code Playgroud)