swift

Protocol defines a path for a method, a property, or constitutes requirements or functionality. The protocol can be adopted by classes, structures, or enumerations to provide the implementation of requirements or functionality. Such classes, structures, or enumerations when adopting one or more protocols must meet their requirements and conform to the protocol.

In other words, the protocol contains the guidelines to which classes and structures must follow. 

Protocol can define methods and properties, it does not care about their implementation, it only sets limits by specifying its type and whether it should provide read-only or read / write (get / set) features. A read-only protocol is more permissive than a protocol where the definitions of both reading and writing methods are claimed.

If, for example, by means of a protocol we specifie that a property is of get and set type, we bind what the property implementation can be, in fact, it must be excluded that it is a constrained or computed property because these are two types of read-only properties.

protocol MyProtocol {

    var itMustBeSet: Int { get set }

    var itMayBeSet: Int { get }

}

 

Let see an example of protocol and its use:

//Protocol definition

protocol FullName {

    var fullName: String { get }

}

 

//Type conformed to the protocol

struct Person: FullName {

    var fullName: String

}

 

The important thing to understand is that for the Person structure to conform to the FullName protocol, you must ensure the implementation of the fullName property.

Back to Repeat: protocol is a constraint, a setting, to which the type conformed to the protocol must follow. It certainly remembers the constraints a daughter class has for a parent class, but is much more versatile because it is not inherited from the types that conform to the protocol. 

We have seen the use of protocol to constrain the presence of a particular property, we now see the use to bind a method.

protocol RandomNumberGenerator {

    func casual() -> Double

}

 

class Casual: RandomNumberGenerator {

 

    let limit: UInt32 = 100

    

    func casual() -> Double {

        return Double(arc4random_uniform(limit))

    }

}