Swift 动态检查元类型一致性

Swift 动态检查元类型一致性,swift,Swift,在Swift中,“is”关键字可用于检查一个元类型是否符合另一个元类型 protocol{} 结构扫帚{} 结构面包:可食用{} func isEdible(itemType:Any.Type)->Bool{ returnitemtype是可食的 } isEdible(Broom.self)//错误 isEdible(Bread.self)//正确 但是,它不适用于动态类型,例如传递到函数中的元类型 func符合(itemType:Any.Type,to target:Any.Type)->B

在Swift中,“is”关键字可用于检查一个元类型是否符合另一个元类型

protocol{}
结构扫帚{}
结构面包:可食用{}
func isEdible(itemType:Any.Type)->Bool{
returnitemtype是可食的
}
isEdible(Broom.self)//错误
isEdible(Bread.self)//正确
但是,它不适用于动态类型,例如传递到函数中的元类型

func符合(itemType:Any.Type,to target:Any.Type)->Bool{
itemType是目标//错误:使用未声明的类型“target”
}
符合(Bread.self,to:eatable.self)
符合(Broom.self,to:eable.self)

是否有任何方法可以通过这种方式测试与动态元类型的一致性?

您可以使用泛型测试一致性:

func conforms<T>(_ itemType: Any.Type, to target: T.Type) -> Bool {
    itemType is T.Type
}
func符合(itemType:Any.Type,to target:T.Type)->Bool{
itemType是T.Type
}