swift - 动态检查元类型一致性
问题描述
在 Swift 中,“is”关键字可用于检查元类型是否符合另一个元类型。
protocol Edible {}
struct Broom {}
struct Bread: Edible {}
func isEdible(_ itemType: Any.Type) -> Bool {
return itemType is Edible.Type
}
isEdible(Broom.self) // false
isEdible(Bread.self) // true
但是,它不适用于动态类型,例如传递给函数的元类型。
func conforms(_ itemType: Any.Type, to target: Any.Type) -> Bool {
itemType is target // Error: Use of undeclared type 'target'
}
conforms(Bread.self, to: Edible.self)
conforms(Broom.self, to: Edible.self)
有没有办法以这种方式测试与动态元类型的一致性?
解决方案
您可以使用泛型测试一致性:
func conforms<T>(_ itemType: Any.Type, to target: T.Type) -> Bool {
itemType is T.Type
}
推荐阅读
- ruby - 获取括号之间的值
- python - Django(1.11)在嵌套序列化程序中发布user.id
- ios - 在 AudioKit 中创建反馈减少过滤器
- pandas - 如何根据值的存在创建pandas DataFrame 列
- java - jvm 1.7 版不适用于本产品。Eclipse in window 需要更高版本 1.8
- timing - Cakeyframeanimation 和 cabasicanimation 时间问题
- php - 如何设置下拉列表的选定值?
- linux - Bash 脚本仅在 bash 脚本文件所在的路径中工作
- apache-tika - 如何从pdf文件中的图像中提取文本?
- azure - 未正确检索存储帐户实体的指标