Swift 中这两者有区别吗?
protocol ABProtocol: AProtocol, BProtocol {}
typealias ABProtocol = AProtocol&BProtocol
为了让事情更清楚,我将第二个重命名为:
typealias ABProtocolIntersection = AProtocol & BProtocol
我可以立即想到两个差异。
如果您的类型符合AProtocol
and BProtocol
,该类型自动成为以下类型的子类型ABProtocolIntersection
, 但它does not自动符合ABProtocol
。毕竟,ABProtocol
是一个完全不同的协议。
Example:
class Foo: AProtocol, BProtocol { ... }
func foo<T: ABProtocolIntersection>(type: T.Type) { }
func bar<T: ABProtocol>(type: T.Type) { }
foo(type: Foo.self) // works
bar(type: Foo.self) // error
另一个区别是你可以添加扩展ABProtocol
, 但不是ABProtocolIntersection
:
extension ABProtocol { } // OK
extension ABProtocolExtension { } // error
这是因为ABProtocolIntersection
是一个非名义类型,类似于这样的类型(Int, Int)
or (Int) -> String
。也可以看看:Swift 中的“非名义类型”是什么?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)