消除协议组成的歧义

时间:2017-03-07 19:49:18

标签: swift protocols composition

是否可以确定撰写的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)

1 个答案:

答案 0 :(得分:2)

编辑:正如@Hamish在评论中所说,这是不可能的。

这里有一个快速的进化建议可以修复它 https://github.com/apple/swift-evolution/blob/91725ee83fa34c81942a634dcdfa9d2441fbd853/proposals/0126-refactor-metatypes-repurpose-t-dot-self-and-mirror.md#known-issues-of-metatypes

它没有进入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