# 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](https://www.hackingwithswift.com/quick-start/beginners/how-to-create-and-use-protocols))

Protocols are rules or minimum requirements (functions and variables)  that classes and structs need to have ([StiftfulThinking](https://www.youtube.com/watch?v=0gM1wmW1Xvc)). We can add whatever we want.

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

### Sample Codes

{% code title="Example 1" %}

```swift
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)
    
}
```

{% endcode %}

### Technical Protocol Inheritance

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

**Sources:** [HWS](https://www.hackingwithswift.com/quick-start/beginners/summary-protocols-and-extensions),&#x20;

### Protocol Conformance

```swift
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](https://www.hackingwithswift.com/quick-start/beginners/how-to-create-and-use-protocol-extensions),&#x20;

####

### get / get set

{ get } : Read

{ get set } : Read & Write&#x20;

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

### self vs Self

**self:** Current Value

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

{% code title="Example 1" %}

```swift
// 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
```

{% endcode %}

### Protocol Extensions

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

{% code title="Example 1" %}

```swift
extension Collection {
    var isNotEmpty: Bool {
        isEmpty == false
    }
}
```

{% endcode %}

{% code title="Example 2" %}

```swift
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
```

{% endcode %}

#### Protocols cannot have boddies, bodies can only be in extensions

```swift
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](https://www.hackingwithswift.com/quick-start/beginners/how-to-use-opaque-return-types),&#x20;

## Sources

### Videos

{% embed url="<https://youtu.be/1-5SXsVd1zY>" %}

{% embed url="<https://www.youtube.com/watch?v=0gM1wmW1Xvc>" %}

### Articles / Documents

* [WWDC15 - Protocol-Oriented Programming in Swift](https://devstreaming-cdn.apple.com/videos/wwdc/2015/408509vyudbqvts/408/hls_vod_mvp.m3u8)
* [Hacking with Swift / 100 days / 13 - Protocols and Extensions](https://www.hackingwithswift.com/100/swiftui/13)

## See Also

* [protocol-vs-class](https://swift.sedatonat.dev/codes/main-pillars-protocol-class-struct-etc./protocol-vs-class "mention")
