Protocol in Swift programming

Tram Ho

Protocol concept

Protocol is understood as a blueprint containing properties, methods and other declarations to perform a certain task, features. Protocol can be implemented by a Class, Struct or Enum.
When implementing a Protocol , we will have to declare and redefine the properties and methods included in that Protocol.

Protocol declaration syntax

Protocol declaration syntax is relatively similar to Class, Struct or Enum

Want Struct, Class or Enum implement one or more Protocol, we declare as follows

In case of implementing implementations for a Subclass, we have to put the name of Superclass (Superclass) before the name of the Protocol

Declare properties and methods in Protocol

Properties in Protocol

To declare properties in Protocol, there must be enough 3 elements

  1. Attribute name
  2. Datatypes
  3. The state of an attribute (get – get set)

Note: The attribute in Protocol must be declared as a var . Because Protocol defaults on these properties as Computed Properties, it is not possible to declare let and must declare a state of get or get set.

Protocol supports keyword “static” to declare attribute of Type instead of Instance (Protocol does not support keyword “class” )

Method in Protocol

Method declaration is similar to Class and Struct but has no {} and no content.
The Protocol supports both Type Function ( “static” declarations) and Instance Function
Note: Protocol does not allow using constants as parameters for methods

If Struct or Enum implement Protocol, but when defining methods, we want to change its properties, we will have to declare the keyword “mutating” (Do Struct and Enum are reference values )

Optional Protocol

When a Protocol contains so many methods that do not want those Protocol implementers to declare everything, we use the Optional Protocol. There are 2 ways to declare Optional Protocol

Method 1: @objc optional

Declare the @objc optional keyword before the attribute, method, and ” @objc ” before the Protocol declaration. This declaration returns the protocol to the Objective-C compiler, so only the class can implement this Protocol

Method 2: Extention Protocol

This is an optional protocol that is suitable for both Struct, Enum and Class.
Note: Stored Properties cannot be declared

Application of Protocol

  1. Protocol can be used as a data type
  2. Use in Delegate Design Pattern (Used to “capture events”, transfer data between ViewController “)
  3. Expand object
  4. Used in many standard Swift libraries (Equable, Comparable, Hasable, Int, …)
  5. POP Programming (Protocol Oriented Programming)
Share the news now

Source : Viblo