Protocols

Overview

Swift is written as Protocol-Oriented Language.

In WWDC15 Apple suggested to always start with Protocol.

like SubClasses, Structs inherit data from Protocol. All the methods in Protocol must exist on Struct. And you cannot change data type of them. (HWS)

Protocols are rules or minimum requirements (functions and variables) that classes and structs need to have (StiftfulThinking). We can add whatever we want.

let cannot be used in Protocols. Only var can be used.

Sample Codes

Example 1
protocol Vehicle {
    
    // Properties
    var name: String { get }  // car, bike, etc.
    var currentPassengers: Int { get set }  // number passengers in default
    
    // Methods
    func estimateTime(for distance: Int) -> Int
    func travel(distance: Int)
    
}

Technical Protocol Inheritance

Even if you not write the name of the protocol, swift understands and runs the protocol in background.

Sources: HWS,

Protocol Conformance

if you want to add class to a struct, add prior to protocols.

Sources: HWS,

get / get set

{ get } : Read

{ get set } : Read & Write

"set" Cannot be alone, always should be with get { get set }

self vs Self

self: Current Value

Self: Current Type (Int, Double, String, etc.)

Protocol Extensions

They let us add functionality to many types all at once.

Protocols cannot have boddies, bodies can only be in extensions

Opaque return types

Sources: HWS,

Sources

Videos

Articles / Documents

See Also

Last updated

Was this helpful?