检查是否符合元类型的动态集合



我想写一个swift函数,在给定一组元类型的情况下,检查另一个元类型是否符合其中任何一个。

泛型在这里不起作用,因为target的类型在编译时是未知的。

protocol Drinkable {}
protocol Edible {}
struct Bread: Edible {}
func conforms<T>(_ itemType: Any.Type, to target: T.Type) -> Bool {
itemType is T.Type
}
func conformsToAny(_ type: Any.Type, to types: [Any.Type]) {
types.contains {type in
conforms(Bread.self, to: type) // 
}
}
conformsToAny(Bread.self, to: [Drinkable.self, Edible.self])

这可能吗?

您想要做的事情是不可能的。由于conforms<T>(_:to:)是泛型的,所以在编译时必须知道泛型参数类型。

你有几个选择。首先,您可以定义一种新方法来检查一种类型是否符合所有有问题的协议:

func isIngestible(_ type: Any.Type) -> Bool {
return conforms(type, to: Drinkable.self)
|| conforms(type, to: Edible.self)
}

或者定义一个新的主协议,使您的其他协议符合:

protocol Ingestible {}
protocol Drinkable: Ingestible {}
protocol Edible: Ingestible {}
struct Bread: Edible {}
struct Tire {}
print(conforms(Bread.self, to: Ingestible.self))
print(conforms(Tire.self, to: Ingestible.self))

相关内容

最新更新