Swift 4 basics - protocols

Protocols:
Something like interfaces, where we describe the methods, properties and requirements of a type without providing implementation.

Here is how to define a protocol:
protocol MyProtocol{
 var a: Int{get set}
 var b: String{get set}
 var readOnlyVar: String{get}
 //var a, b, and c will have to be listed as properties in any class implementing the protocol
 func getBSquared() -> Int
//this method will have to be defined and implemented in the class that implements this protocol
}

To implement it in a structure:
struct MyStruct: MyProtocol{}
A structure can implement more than one protocol:
struct MyStruct: Proto1, Proto2, Proto3{}

If a class both implements and inherits, we can define the class by inheriting first, then by implementing:
Class MyClass: TheParentClass, Proto1, Proto2{}

Protocols can be used as types
var aProto = Proto1
Can be stored in arrays:
var proto: [Proto1] = []

You however, cannot create an instance of a protocol. You can create an instance of a class or structure that has implemented the protocol. 

Polymorphism: 
When you can use a Protocol as a type for multiple classes that implement it:
for proto1 in protocollection
{
  if proto1 is classThatImplementedProto1 {}
}
You can do this using a switch case as well:
for proto1 in proto1Collection
{
 switch proto1{
case is ClassA: ...
case is ClassB: ...
default: ...
}

You can filter a collection of that protocol as well:
for proto1 in proto1Collection where proto1 is ClassA{}
To typecast all the protocols in a collection:

for proto1 in proto1collection
{
 if let p = proto1 as? ClassA {}
}

Protocol Extensions
What if there is a standard method for all classes that implement a protocol? 
You want to have it as a protocol, yet when you update the internal workings of that protocol, the classes that implement that protocol will have it updated as well. This is when you can make use of protocol extensions:

protocol CowProtocol{
var colour: String {get set}
}

extension CowProtocol{ 
func moo()->{return "Moooo"}
}

class AustralianCow: CowProtocol
{
 var colour: Strin
}

When calling the method:
var ac = AustralianCow()
ac.moo()

A protocol can inherit from other protocols:
protocol Proto1{var a: Int{get set}}
protocol Proto2: Proto1{var b: String{get}}

If proto1 has an extension, proto2 will inherit all of the functions in that extension.

An example of the use of protocols:
protocol Animal{}
protocol Mammal: Animal{}
class Cow: Mammal{}

Iterating through multiple types of a protocol (Animal) using enumerations:
var animals = [Animal]()
animals.append(Cow())
animals.append(Frog())
for (index, animal) in animals.enumerated()
{
 if let _ = animal as? Mammal {}
 if let _ = animal as? Amphibian{}
}

Filtering:
for (index, animal) in animals.enumerated() where animal is Mammal {}



Comments

Popular posts from this blog

Setting up a playground

Go to another page