是否可以确定撰写的Any.Type
是否包含特定的Any.Type
?
(A & B).self
包含A.self
=>真
(B & C).self
包含A.self
=>假
代码示例
protocol A {}
protocol B {}
typealias AB = A & B
func conformsToA(_ type: Any.Type) -> Bool {
return type == A.self
}
print(conformsToA(A.self)) // true
print(conformsToA(AB.self)) // false (but should be true)
我可以在type == (A & B).self
内添加conformsToA(_:)
的特定条款,但这很快就会变得无法管理。想象一下如果引入协议C-Z并且我试图检查类似的东西:
conformsToA((A & C & E & Z).self)
使用Alistra第二种方法的另一种尝试
protocol A {}
protocol B {}
typealias AB = A & B
func conformsToA<T>(_ t1: T.Type) -> Bool {
return T.self is A
}
print(conformsToA(A.self)) // false (but should be true)
print(conformsToA(AB.self)) // false (but should be true)
答案 0 :(得分:2)
编辑:正如@Hamish在评论中所说,这是不可能的。
它没有进入Swift 4 Stage 2。
您可以使用泛型和is
protocol A {}
protocol B {}
protocol C {}
typealias AB = A & B
typealias ABC = A & B & C
func conformsTo<T>(_ object: Any, t: T.Type) -> Bool {
return object.self is T
}
class CL : AB {}
print(conformsTo(CL(), t: A.self)) // true
print(conformsTo(CL(), t: AB.self)) // true
print(conformsTo(CL(), t: ABC.self)) // false
或没有类的实例
protocol A {}
protocol B {}
protocol C {}
typealias AB = A & B
typealias ABC = A & B & C
func conformsTo<T, U>(_ t1: T.Type, t2: U.Type) -> Bool {
return T.self is U.Type
}
print(conformsTo(ABC.self, t2: A.self)) // false
print(conformsTo(ABC.self, t2: AB.self)) // false
print(conformsTo(ABC.self, t2: ABC.self)) // true
print(conformsTo(AB.self, t2: A.self)) // false
print(conformsTo(AB.self, t2: AB.self)) // true
print(conformsTo(AB.self, t2: ABC.self)) // false
print(conformsTo(A.self, t2: A.self)) // true
print(conformsTo(A.self, t2: AB.self)) // false
print(conformsTo(A.self, t2: ABC.self)) // false