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

struct stc_Name: cls_1, cls2, prc_1, prc_2 {
    // codes...
    }

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.)

Example 1
// Variant 1
extension Int {
    func squared() -> Int {
        self * self
    }
}

// Variant 2
extension Numeric {
    func squared() -> Self {
        self * self
    }
}

let wholeNumber = 5
print(wholeNumber.squared())

// print: 25

Protocol Extensions

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

Example 1
extension Collection {
    var isNotEmpty: Bool {
        isEmpty == false
    }
}
Example 2
protocol Person {
    var name: String { get }
    func sayHello()
}

extension Person {
    func sayHello() {
        print("Hi, I'm \(name)")
    }
}

struct Employee: Person {
    let name: String
}

let taylor = Employee(name: "Taylor Swift")
taylor.sayHello()

// print: Hi I'm Taylor Swift

Protocols cannot have boddies, bodies can only be in extensions

protocol Building {
    var type: String { get }
    var rooms: Int { get }
    var cost: Int { get set }
    var agent: String { get set }
//    func printSummary()
    func printSummary() {  // Error: Protocol methods must not have bodies
        print("Talk to \(agent) to buy this \(type) for $\(cost).")
    }
}

//extension Building {
//    func printSummary() {
//        print("Talk to \(agent) to buy this \(type) for $\(cost).")
//    }
//}

Opaque return types

Sources: HWS,

Sources

Videos

Articles / Documents

See Also

Last updated