假设我有一个类型为Any
的变量,并且我想知道这是否是一个数组,这是我想做的:
if myVariable is Array { /* Do what I want */ }
但是Swift需要提供数组的通用类型,例如:
if myVariable is Array<Int> { }
但是我不想检查泛型类型,我只是想知道这是否是一个数组,我试过了:
if myVariable is Array<Any> { }
希望它可以匹配每种类型的数组,但是也不起作用...(它不匹配所有类型的数组,因此,如果我的变量是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"
最佳答案
这里有两件事可能对您有用。
选项1:
请注意,child
是一个元组,其中包含带有属性名称(示例中为String?
)和项目名称的"property"
。因此,您需要查看child.1
。
在这种情况下,您应该检查:
if String(describing: type(of: child.1)).hasPrefix("Foo<")
选项2:
如果创建由
FooProtocol
实现的协议(protocol)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
}
}