Swift语言中的Protocol

Protocol即协议,字面意思。

Swift语言中的Protocol

在Swift语言的官方教程中,这样描述Protocol:

A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol doesn’t actually provide an implementation for any of these requirements—it only describes what an implementation will look like. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to conform to that protocol.

大致意思是:Protocol对特定任务或功能的方法、属性以及其它需求进行了蓝图层面的定义。Protocol本身并不实现这些需求,它只是对实现这些需求的代码看起来应该是什么样子进行了描述。然后遵循该Protocol的class, structure和enumeration就可以根据描述去实现具体的功能。任何满足该Protocol需求的类型都可以描述为遵循该Protocol