1

So I came across the subject of protocols and I have searched the internet a bunch for an answer but I couldn't find one, atleast one that solved my problem.

So I understand that Protocols are a "blueprint" of methods, properties and such and that it can be implemented in a class or struct and that it needs to conform to its requirements and such, but why would one use one?

I mean you could also just create a function inside a struct itself. It seems a bit of a hassle to write a protocol and then for the implementation of said protocol you would have to write all the requirements again with more code this time.

Is there a particular reason why one would use a protocol? Is it for safety of your code or some other reason?

For example:

In swift you have the CustomStringConvertible protocol which has a required computed property to control how custom types are represented as a printable String value, but you could also create a function inside your class which could solve this issue aswel. You could even have computed property which does the same as this protocol without even implementing this protocol.

So if someone could please shed some light onto this subject, that would be great.

Thank you in advance!

Dutchveteran
  • 73
  • 1
  • 4
  • Because you might want to be able to use multiple different implementation classes that all implement the same methods. Look up justification for Java interfaces, because it's the same purpose. – Carcigenicate Nov 18 '18 at 14:19
  • You can use Protocols to allow different classes that aren't necessary linked at all (don't have the same use, same parent class) to force them to have some methods. – Larme Nov 18 '18 at 14:19
  • Possibly Related: https://stackoverflow.com/questions/46496485/when-to-use-protocol-in-swift – Ahmad F Nov 18 '18 at 14:39
  • 2
    Possible duplicate of [What is Protocol Oriented Programming in Swift? What added value does it bring?](https://stackoverflow.com/questions/37530346/what-is-protocol-oriented-programming-in-swift-what-added-value-does-it-bring) – mfaani Nov 18 '18 at 20:17
  • Also semi-related: https://stackoverflow.com/questions/41706504/why-should-not-directly-extend-uiview-or-uiviewcontroller – mfaani Nov 18 '18 at 20:17

3 Answers3

7

but why would one use one?

Protocols in swift are similar to Abstractions in some other languages.

before answering your question, we have to clear things out, Protocols declaration could be various but considering you have already read tons of it,

It will also be great to mention this answer here.

Now lets get into the real use case here.

Consider you have this protocol.

protocol Printable {
var name: String { get }
}

Now we need some type of structs or classes to confirm to it, or Multiple ones.

And here where it lays one of the biggest benefit of it.

Consider you have to print the name propriety of an objects.

For example those.

struct Human {
    var name: String
}
struct Animal {
    var name: String
}

You would simply type this without Protocols

    func printOut(human: Human){
    human.name
   }

   func printOut(animal: Animal){
    animal.name    
   }

Which is correct, now observe the code below using protocol Printable.

struct Human: Printable {
    var name: String
}
struct Animal: Printable {
    var name: String
}

 func printOut(object: Printable){
    print(object.name)
   }

It only takes us one func and so on using the Protocols.

Conclusion

Protocols used to minimize the unnecessary chunks of code.

It's name represent the effect applied on the confirm party.

Protocols can be injected as parameters types.

You can also read more about them here.

And more about the use cases here.

Mohmmad S
  • 5,001
  • 4
  • 18
  • 50
1

Protocol in swift is a pattern for allowing your classes to confirm to particular set of rules.

In other words a protocol is a blueprint of methods and properties that are necessary for a particular task.

You implement a protocol by confirming to it. If your class miss implementation of any method defined in the protocol, swift compiler tells you.

As an example lets consider that you want to make a Car class. Now there are particular requirements for a car. Like it has wheels, a trunk, etc. Each requirement can be defined as a protocol that is then implemented by the Car class. If your class don't have a trunk, you just drop the implementation.

Protocol oriented programming is a new programming paradigm. That solves some problems incurred by object oriented programming. Like multiple inheritance. Swift doesn't allow multiple inheritance but it allows confirmation to multiple protocols.

It's very easy to remove some functionality from a class in Protocol oriented programming. You just stop conforming to it. Comparative to OOP its very easy to do such things in POP.

HAK
  • 2,023
  • 19
  • 26
0

The concept of the protocol is very simple: it's nothing more than a promise that specific methods and/or properties will exist in whatever object has taken on that protocol. And so we use them for typing and type safety.

Imagine creating a custom control, like an action sheet:

class CustomActionSheet: UIControl {

    func userTappedOnSomething() {
        // user tapped on something
    }

}

...and you implemented it in one of your view controllers.

class SomeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let actionSheet = CustomActionSheet()
    }

}

This isn't much use without allowing the action sheet to communicate with the view controller when the user taps on a button. So we use a delegate:

class CustomActionSheet: UIControl {

    weak var delegate: UIViewController?

    func userTappedOnSomething() {
        delegate?.userTookAction()
    }

}

class SomeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let actionSheet = CustomActionSheet()
        actionSheet.delegate = self

    }

    func userTookAction() {
        // update the UI
    }

}

Now when the user taps on a button in the action sheet, the view controller underneath can update its UI. But this actually won't compile. You will get an error that UIViewController has no member userTookAction. That is because the UIViewController class doesn't have a method called userTookAction, only this instance of the view controller does. So we use a protocol:

protocol ActionSheetProtocol: AnyObject {
    func userTookAction()
}

This protocol says that whatever object that conforms to it must include this method. So we change the action sheet's delegate to be of that protocol type and we conform the view controller to that protocol since it has such method:

class CustomActionSheet: UIControl {

    weak var delegate: ActionSheetProtocol?

    func userTappedOnSomething() {
        delegate?.userTookAction()
    }

}

class SomeViewController: UIViewController, ActionSheetProtocol {

    override func viewDidLoad() {
        super.viewDidLoad()

        let actionSheet = CustomActionSheet()
        actionSheet.delegate = self

    }

    func userTookAction() {
        // update the UI
    }

}

This is a classic example of protocol use in Swift and once you understand it, you will learn how to get crafty with protocols and use them in very clever ways. But no matter how you use them, the concept remains: promises that things will exist.

Note: In this example, I named the protocol ActionSheetProtocol, because to someone learning protocols, it makes the most sense. However, in the Swift world, in today's practice, most programmers (including the guys at Apple) would name it ActionSheetDelegate. This can be confusing for someone learning protocols so in this example I tried to make it as clear as possible. I personally don't like naming protocols delegates but there’s a lot of things I don’t like.

Note 2: I also made the protocol of type AnyObject which is Swift's syntax for making the protocol a class protocol. Not all protocols need to be of type AnyObject.

trndjc
  • 11,654
  • 3
  • 38
  • 51