2
2
.
.
4
4
.
.
4
4
P
P
r
r
o
o
t
t
o
o
c
c
o
o
l
l
s
s
I
I
n
n
f
f
o
o
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.
P
P
r
r
o
o
t
t
o
o
c
c
o
o
l
l
S
S
y
y
n
n
t
t
a
a
x
x
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)
A
A
s
s
s
s
o
o
c
c
i
i
a
a
t
t
e
e
d
d
T
T
y
y
p
p
e
e
Keyword associatedtype is used to specify that certain Methods or Properties must have the same Type but without
specifying exactly which one (serving the same purpose as Generics do for Types).
Type is later declared by the Type that implements Protocol (like Generic Type is declared when creating Instance).
In this example we use associatedtype to define that Property name must be of the same Type as instance returned by
getName(). Employee that adopts Protocol defines that mytype will be String by declaring it at the same places where
mytype appears in Protocol.
Test.swift
protocol Person {
associatedtype mytype
var name : mytype { get set }
func getName () -> mytype
}
struct Employee : Person {
var name : String
func getName () -> String { return name }
}
var name = Employee(name: "John").getName()
print(name)