【问题标题】:Check conformance to a dynamic collection of metatypes检查对元类型动态集合的一致性
【发布时间】:2020-08-16 10:33:38
【问题描述】:

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


【解决方案1】:

你想做的事情是不可能的。由于conforms&lt;T&gt;(_: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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多