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

问题描述

我想写一个 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])

这可能吗?

标签: swift

解决方案


你想做的事情是不可能的。由于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))

推荐阅读