首页 > 解决方案 > 动态检查元类型一致性

问题描述

在 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)

有没有办法以这种方式测试与动态元类型的一致性?

标签: swift

解决方案


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

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

推荐阅读