[英]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.