swift - 检查对元类型动态集合的一致性
问题描述
我想写一个 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))
推荐阅读
- python - tensorflow:如何使用 flags.DEFINE_multi_float()
- java - 在 null 问题上找不到属性或字段
- python - 如何根据先前的键值打印字典的值?(其中关键是日期)
- javascript - 当角度选择下拉事件完成时进行计算
- ios - 使用一个 CBManager 连接和写入多个外围设备
- javascript - react js中的日期转换
- sql - 按时间范围谷歌选择不同的用户组 - bigquery SQL
- android - 当应用程序关闭时我需要一个屏幕提醒像这样的示例屏幕图像
- java - 如何在一个 JText 区域中显示大量价值 JTable 选定的行
- scikit-learn - 使用 scikit-learn LinearRegression.predict() 遇到维度问题