[英]Use Swift `is` to check type of generic type
假设我有一个Any
类型的变量,我想知道这是否是一个数组,这就是我想做的:
if myVariable is Array { /* Do what I want */ }
但是 Swift 需要给出数组的泛型类型,例如:
if myVariable is Array<Int> { }
但我不想检查泛型类型,我只想知道这是否是一个数组,我试过:
if myVariable is Array<Any> { }
希望它能匹配每种类型的数组,但这也不起作用......(它不匹配所有类型的 arrays,所以如果我的变量是一个 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?
的元组String?
带有属性的名称(在您的示例中为"property"
)和项目。 因此,您需要查看child.1
。
在这种情况下,您应该检查:
if String(describing: type(of: child.1)).hasPrefix("Foo<")
选项2:
如果创建由Foo<T>
实现的协议FooProtocol
,则可以检查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
}
}
在 Java 你想使用Array<?>
,在 Swift 这是不可能的,但你可以模拟它。
创建协议protocol AnyArray {}
现在让所有 arrays 实现这个协议: extension Array: AnyArray {}
现在您可以轻松地做您想做的事情:
if myVariable is AnyArray {... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.