When and why would i use Protocols in Swift?












0















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!










share|improve this question























  • 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: stackoverflow.com/questions/46496485/…

    – Ahmad F
    Nov 18 '18 at 14:39






  • 1





    Possible duplicate of What is Protocol Oriented Programming in Swift? What added value does it bring?

    – Honey
    Nov 18 '18 at 20:17











  • Also semi-related: stackoverflow.com/questions/41706504/…

    – Honey
    Nov 18 '18 at 20:17
















0















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!










share|improve this question























  • 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: stackoverflow.com/questions/46496485/…

    – Ahmad F
    Nov 18 '18 at 14:39






  • 1





    Possible duplicate of What is Protocol Oriented Programming in Swift? What added value does it bring?

    – Honey
    Nov 18 '18 at 20:17











  • Also semi-related: stackoverflow.com/questions/41706504/…

    – Honey
    Nov 18 '18 at 20:17














0












0








0








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!










share|improve this question














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!







swift protocols swift-protocols customstringconvertible






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 18 '18 at 14:13









DutchveteranDutchveteran

283




283













  • 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: stackoverflow.com/questions/46496485/…

    – Ahmad F
    Nov 18 '18 at 14:39






  • 1





    Possible duplicate of What is Protocol Oriented Programming in Swift? What added value does it bring?

    – Honey
    Nov 18 '18 at 20:17











  • Also semi-related: stackoverflow.com/questions/41706504/…

    – Honey
    Nov 18 '18 at 20:17



















  • 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: stackoverflow.com/questions/46496485/…

    – Ahmad F
    Nov 18 '18 at 14:39






  • 1





    Possible duplicate of What is Protocol Oriented Programming in Swift? What added value does it bring?

    – Honey
    Nov 18 '18 at 20:17











  • Also semi-related: stackoverflow.com/questions/41706504/…

    – Honey
    Nov 18 '18 at 20:17

















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







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





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: stackoverflow.com/questions/46496485/…

– Ahmad F
Nov 18 '18 at 14:39





Possibly Related: stackoverflow.com/questions/46496485/…

– Ahmad F
Nov 18 '18 at 14:39




1




1





Possible duplicate of What is Protocol Oriented Programming in Swift? What added value does it bring?

– Honey
Nov 18 '18 at 20:17





Possible duplicate of What is Protocol Oriented Programming in Swift? What added value does it bring?

– Honey
Nov 18 '18 at 20:17













Also semi-related: stackoverflow.com/questions/41706504/…

– Honey
Nov 18 '18 at 20:17





Also semi-related: stackoverflow.com/questions/41706504/…

– Honey
Nov 18 '18 at 20:17












3 Answers
3






active

oldest

votes


















1















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.






share|improve this answer































    0














    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.






    share|improve this answer































      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.






      share|improve this answer

























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53361823%2fwhen-and-why-would-i-use-protocols-in-swift%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        1















        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.






        share|improve this answer




























          1















          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.






          share|improve this answer


























            1












            1








            1








            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.






            share|improve this answer














            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.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 18 '18 at 14:36









            Mohmmad SMohmmad S

            1,6381418




            1,6381418

























                0














                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.






                share|improve this answer




























                  0














                  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.






                  share|improve this answer


























                    0












                    0








                    0







                    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.






                    share|improve this answer













                    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.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 18 '18 at 14:56









                    HAKHAK

                    958716




                    958716























                        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.






                        share|improve this answer






























                          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.






                          share|improve this answer




























                            0












                            0








                            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.






                            share|improve this answer















                            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.







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 18 '18 at 23:04

























                            answered Nov 18 '18 at 17:18









                            bsodbsod

                            2,2061822




                            2,2061822






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53361823%2fwhen-and-why-would-i-use-protocols-in-swift%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                這個網誌中的熱門文章

                                Academy of Television Arts & Sciences

                                L'Équipe

                                1995 France bombings