Protocols declare signatures of Properties and Methods. (without implementation)
They are like interfaces in other Languages. (Interface can only declare Methods)
Multiple Protocols can be adopted by Class, Struct or Enumerator. (which must implement its Properties and Methods)
Properties are declared in a special way using
● { get } to specify that Property should be read only
● { get set } to specify that Property should be read & write
These define minimum requirements for a Property which means that if
● Property is declared as { get } Class can declare Property that is either read only or read & write
● Property is declared as { get set } Class must declare Property that must be both read & write
Function might have Protocol as Input Parameter or return value. This means that Instance that will be given for such
Parameter or returned by Function must be of Type (Struct, Class or Enumerator) that adopts such Protocol.
At these places you can use Self as alias for a Type that implements Protocol.
Protocol is declared by
● using Keyword protocol
● followed by the Name Person
● followed by the Body
● which can have Properties var name : String { get set }
Methods func sayHello (name: String) -> (String)
Protocol Syntax
//DECLARE PROTOCOL.
protocol Person {
//DECLARE PROPERTIES.
var greet : String { get }
var name : String { get set }
//DECLARE METHODS.
func sayHello (name: String) -> (String)
}
//DECLARE STRUCT.
struct Employee : Person { //struct adopts Protocol Person
//DECLARE PROPERTIES.
let greet : String = "Hello"
var name : String
//DECLARE METHOD.
func sayHello (name: String) -> (String) {
return("\(greet) \(name)")
}
}
//CREATE STRUCT INSTANCE.
var john = Employee(name: "Unknown")
var greeting = john.sayHello(name: "John")
print(greeting)