Page 212

31. Swift – Protocols


Protocols provide a blueprint for Methods, properties and other requirements functionality. It is just described as a methods or properties skeleton instead of implementation. Methods and properties implementation can further be done by defining classes, functions and enumerations. Conformance of a protocol is defined as the methods or properties satisfying the requirements of the protocol.

Syntax Protocols also follow the similar syntax as that of classes, structures, and enumerations: protocol SomeProtocol { // protocol definition } Protocols are declared after the class, structure or enumeration type names. Single and Multiple protocol declarations are also possible. If multiple protocols are defined they have to be separated by commas. struct SomeStructure: Protocol1, Protocol2 { // structure definition } When a protocol has to be defined for super class, the protocol name should follow the super class name with a comma. class SomeClass: SomeSuperclass, Protocol1, Protocol2 { // class definition }

Property and Method Requirements Protocol is used to specify particular class type property or instance property. It just specifies the type or instance property alone rather than specifying whether it is a stored or computed property. Also, it is used to specify whether the property is 'gettable' or 'settable'. Property requirements are declared by 'var' keyword as property variables. {get set} is used to declare gettable and settable properties after their type declaration. Gettable is mentioned by {get} property after their type declaration.


​Swift is just a effective and user-friendly programming language for macOS, iOS, watchOS and ...