(空)协议一致性测试

时间:2019-02-10 03:59:42

标签: ios swift generics protocols

这让我有些困惑。

我已出于测试目的定义了此空协议:

protocol Doable {
}

协议为空,我希望任何可能的类型都符合它。

但是当我使用此代码执行简单的协议一致性测试时,有两种方法。

if let _ = MyType.self as? Doable {
    print("Doable match OK!!")
} else {
    print("That doesn't match!!")
}

if MyType.self is Doable.Type {
    print("Doable match OK!!")
} else {
    print("That doesn't match!!")
}

我总是得到以下结果:它不匹配

那应该发生什么吗?

还是我的测验或期望错了?

2 个答案:

答案 0 :(得分:2)

即使类型满足协议要求,也必须明确说明其一致性。

答案 1 :(得分:1)

Swift类型仅在显式实现时才符合协议。

要向(例如)标准类型(例如String)添加协议一致性,您可以:

extension String: Doable {}
let aString = ""
if aString is Doable {
 print("it works")
}

Apple documentation on protocols

中查看有关其工作原理的更多详细信息

您还可以查看条件一致性,这是一种Swift 4功能,可以满足您的需求。 Conditional conformance

注意

在实际代码中,该测试没有用,因为Swift编译器在这种情况下知道 String 可行