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

时间:2017-01-08 15:47:42

标签: swift generics

让我们说我有一个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"

2 个答案:

答案 0 :(得分:3)

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

选项1:

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

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

if String(describing: type(of: child.1)).hasPrefix("Foo<")

选项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
    }
}

答案 1 :(得分:0)

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

let conforms = T.self is MyProtocol.Type

查看此信息:Swift: check if generic type conforms to protocol