gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:58:16 25 4
gpt4 key购买 nike

假设我有一个 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:

如果您创建协议(protocol) FooProtocolFoo<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
}
}

关于swift - 使用 Swift `is` 检查泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41534512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com