Difference between computed property and property set with closure












47















I'm new to Swift. What is the difference between a computed property and a property set to a closure? I know a computed property gets recalculated each time. Is it different for the closure? i.e.



Closure:



var pushBehavior: UIPushBehavior = {
let lazilyCreatedPush = UIPushBehavior()
lazilyCreatedPush.setAngle(50, magnitude: 50)
return lazilyCreatedPush
}()


Computed:



var pushBehavior: UIPushBehavior {
get{
let lazilyCreatedPush = UIPushBehavior()
lazilyCreatedPush.setAngle(50, magnitude: 50)
return lazilyCreatedPush
}
}









share|improve this question





























    47















    I'm new to Swift. What is the difference between a computed property and a property set to a closure? I know a computed property gets recalculated each time. Is it different for the closure? i.e.



    Closure:



    var pushBehavior: UIPushBehavior = {
    let lazilyCreatedPush = UIPushBehavior()
    lazilyCreatedPush.setAngle(50, magnitude: 50)
    return lazilyCreatedPush
    }()


    Computed:



    var pushBehavior: UIPushBehavior {
    get{
    let lazilyCreatedPush = UIPushBehavior()
    lazilyCreatedPush.setAngle(50, magnitude: 50)
    return lazilyCreatedPush
    }
    }









    share|improve this question



























      47












      47








      47


      22






      I'm new to Swift. What is the difference between a computed property and a property set to a closure? I know a computed property gets recalculated each time. Is it different for the closure? i.e.



      Closure:



      var pushBehavior: UIPushBehavior = {
      let lazilyCreatedPush = UIPushBehavior()
      lazilyCreatedPush.setAngle(50, magnitude: 50)
      return lazilyCreatedPush
      }()


      Computed:



      var pushBehavior: UIPushBehavior {
      get{
      let lazilyCreatedPush = UIPushBehavior()
      lazilyCreatedPush.setAngle(50, magnitude: 50)
      return lazilyCreatedPush
      }
      }









      share|improve this question
















      I'm new to Swift. What is the difference between a computed property and a property set to a closure? I know a computed property gets recalculated each time. Is it different for the closure? i.e.



      Closure:



      var pushBehavior: UIPushBehavior = {
      let lazilyCreatedPush = UIPushBehavior()
      lazilyCreatedPush.setAngle(50, magnitude: 50)
      return lazilyCreatedPush
      }()


      Computed:



      var pushBehavior: UIPushBehavior {
      get{
      let lazilyCreatedPush = UIPushBehavior()
      lazilyCreatedPush.setAngle(50, magnitude: 50)
      return lazilyCreatedPush
      }
      }






      swift computed-properties






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jul 2 '18 at 21:36







      bakalolo

















      asked Jul 20 '15 at 11:51









      bakalolobakalolo

      9951025




      9951025
























          4 Answers
          4






          active

          oldest

          votes


















          82














          The first is a stored property that is initialized via a closure. The second is a computed property.



          The stored property's initialization closure is called once and only once, but you can later change the value of the stored property (unless you replace var with let). This is useful when you want to encapsulate the code to initialize a stored property in a single, concise block of code.



          The computed property's block, however, is called each time you reference the variable. It’s useful when you want the code to be called every time you reference the computed property. Generally you do this when the computed property needs to be recalculated every time you reference the stored property (e.g. recalculated from other, possibly private, stored properties).



          In this case, you undoubtedly want the stored property (the first example), not the computed property (the second example). You presumably don't want a new push behavior object each time you reference the variable.





          By the way, in your first example, you internally reference to it being instantiated lazily. If you want that behavior, you must use the lazy keyword:



          lazy var pushBehavior: UIPushBehavior = {
          let lazilyCreatedPush = UIPushBehavior()
          lazilyCreatedPush.setAngle(50, magnitude: 50)
          return lazilyCreatedPush
          }()


          If, however, the property is static, it is automatically instantiated lazily.






          share|improve this answer





















          • 2





            Awesome explanation..!! ;)

            – itsji10dra
            Mar 7 '17 at 7:32



















          5














          The main difference is that you cannot assign something to the computed property since it has no setter. In this case the closure only gets called once and the return value gets stored in the variable so if the outcome doesn't change over time it is more efficient to use the stored variable rather than the computed one.



          In general: computed properties should only be used if the value can be retrieved quickly.



          Sidenote: If you don't change/reassign the stored variable you should consider making it a constant (let)






          share|improve this answer































            5














            Closure :



              //closure
            var pushBehavior: UIPushBehavior = {
            let lazilyCreatedPush = UIPushBehavior()
            lazilyCreatedPush.setAngle(50, magnitude: 50)
            return lazilyCreatedPush
            }()


            At first time when pushBehavior variable called then block execute and value is saved in pushBehavior variable. after that whenever you call pushBehavior then those value are returned.



            means only first-time block code executed and saved in this variable.
            Also, you can store variable value whenever you want but after that, those value returned but if you declare as "let" then you can't change this value.



            Computed property :



            var pushBehavior: UIPushBehavior {
            get{
            let lazilyCreatedPush = UIPushBehavior()
            lazilyCreatedPush.setAngle(50, magnitude: 50)
            return lazilyCreatedPush
            }
            }


            In computed property whenever you called pushBehavior variable then this block execute and value return. so every time block is executed.
            and you can not declare variable as "let" keyword for pushBehavior variable.



            So you can use this code as per your requirement.






            share|improve this answer


























            • The closure one will be initialized immediately whether or not you use it or not. It is not lazily initialize. BTW, capitalize the first word after a period, it makes reading a little bit more pleasant.

              – Kent Liau
              Dec 27 '16 at 3:58





















            0














            This isn't an answer, but it's just worth mentioning that for:




            • A stored properties the value must be known after initialization. That happens either by defaulting or through initialization.

            • A computed property's value isn't computed until it's accessed

            • A lazy loaded property's value isn't defined until it's accessed


            hence for both computed and lazy variables you can access self or stored properties with no worries.






            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%2f31515805%2fdifference-between-computed-property-and-property-set-with-closure%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              4 Answers
              4






              active

              oldest

              votes








              4 Answers
              4






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              82














              The first is a stored property that is initialized via a closure. The second is a computed property.



              The stored property's initialization closure is called once and only once, but you can later change the value of the stored property (unless you replace var with let). This is useful when you want to encapsulate the code to initialize a stored property in a single, concise block of code.



              The computed property's block, however, is called each time you reference the variable. It’s useful when you want the code to be called every time you reference the computed property. Generally you do this when the computed property needs to be recalculated every time you reference the stored property (e.g. recalculated from other, possibly private, stored properties).



              In this case, you undoubtedly want the stored property (the first example), not the computed property (the second example). You presumably don't want a new push behavior object each time you reference the variable.





              By the way, in your first example, you internally reference to it being instantiated lazily. If you want that behavior, you must use the lazy keyword:



              lazy var pushBehavior: UIPushBehavior = {
              let lazilyCreatedPush = UIPushBehavior()
              lazilyCreatedPush.setAngle(50, magnitude: 50)
              return lazilyCreatedPush
              }()


              If, however, the property is static, it is automatically instantiated lazily.






              share|improve this answer





















              • 2





                Awesome explanation..!! ;)

                – itsji10dra
                Mar 7 '17 at 7:32
















              82














              The first is a stored property that is initialized via a closure. The second is a computed property.



              The stored property's initialization closure is called once and only once, but you can later change the value of the stored property (unless you replace var with let). This is useful when you want to encapsulate the code to initialize a stored property in a single, concise block of code.



              The computed property's block, however, is called each time you reference the variable. It’s useful when you want the code to be called every time you reference the computed property. Generally you do this when the computed property needs to be recalculated every time you reference the stored property (e.g. recalculated from other, possibly private, stored properties).



              In this case, you undoubtedly want the stored property (the first example), not the computed property (the second example). You presumably don't want a new push behavior object each time you reference the variable.





              By the way, in your first example, you internally reference to it being instantiated lazily. If you want that behavior, you must use the lazy keyword:



              lazy var pushBehavior: UIPushBehavior = {
              let lazilyCreatedPush = UIPushBehavior()
              lazilyCreatedPush.setAngle(50, magnitude: 50)
              return lazilyCreatedPush
              }()


              If, however, the property is static, it is automatically instantiated lazily.






              share|improve this answer





















              • 2





                Awesome explanation..!! ;)

                – itsji10dra
                Mar 7 '17 at 7:32














              82












              82








              82







              The first is a stored property that is initialized via a closure. The second is a computed property.



              The stored property's initialization closure is called once and only once, but you can later change the value of the stored property (unless you replace var with let). This is useful when you want to encapsulate the code to initialize a stored property in a single, concise block of code.



              The computed property's block, however, is called each time you reference the variable. It’s useful when you want the code to be called every time you reference the computed property. Generally you do this when the computed property needs to be recalculated every time you reference the stored property (e.g. recalculated from other, possibly private, stored properties).



              In this case, you undoubtedly want the stored property (the first example), not the computed property (the second example). You presumably don't want a new push behavior object each time you reference the variable.





              By the way, in your first example, you internally reference to it being instantiated lazily. If you want that behavior, you must use the lazy keyword:



              lazy var pushBehavior: UIPushBehavior = {
              let lazilyCreatedPush = UIPushBehavior()
              lazilyCreatedPush.setAngle(50, magnitude: 50)
              return lazilyCreatedPush
              }()


              If, however, the property is static, it is automatically instantiated lazily.






              share|improve this answer















              The first is a stored property that is initialized via a closure. The second is a computed property.



              The stored property's initialization closure is called once and only once, but you can later change the value of the stored property (unless you replace var with let). This is useful when you want to encapsulate the code to initialize a stored property in a single, concise block of code.



              The computed property's block, however, is called each time you reference the variable. It’s useful when you want the code to be called every time you reference the computed property. Generally you do this when the computed property needs to be recalculated every time you reference the stored property (e.g. recalculated from other, possibly private, stored properties).



              In this case, you undoubtedly want the stored property (the first example), not the computed property (the second example). You presumably don't want a new push behavior object each time you reference the variable.





              By the way, in your first example, you internally reference to it being instantiated lazily. If you want that behavior, you must use the lazy keyword:



              lazy var pushBehavior: UIPushBehavior = {
              let lazilyCreatedPush = UIPushBehavior()
              lazilyCreatedPush.setAngle(50, magnitude: 50)
              return lazilyCreatedPush
              }()


              If, however, the property is static, it is automatically instantiated lazily.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Jun 18 '18 at 16:37

























              answered Jul 20 '15 at 12:05









              RobRob

              302k49564734




              302k49564734








              • 2





                Awesome explanation..!! ;)

                – itsji10dra
                Mar 7 '17 at 7:32














              • 2





                Awesome explanation..!! ;)

                – itsji10dra
                Mar 7 '17 at 7:32








              2




              2





              Awesome explanation..!! ;)

              – itsji10dra
              Mar 7 '17 at 7:32





              Awesome explanation..!! ;)

              – itsji10dra
              Mar 7 '17 at 7:32













              5














              The main difference is that you cannot assign something to the computed property since it has no setter. In this case the closure only gets called once and the return value gets stored in the variable so if the outcome doesn't change over time it is more efficient to use the stored variable rather than the computed one.



              In general: computed properties should only be used if the value can be retrieved quickly.



              Sidenote: If you don't change/reassign the stored variable you should consider making it a constant (let)






              share|improve this answer




























                5














                The main difference is that you cannot assign something to the computed property since it has no setter. In this case the closure only gets called once and the return value gets stored in the variable so if the outcome doesn't change over time it is more efficient to use the stored variable rather than the computed one.



                In general: computed properties should only be used if the value can be retrieved quickly.



                Sidenote: If you don't change/reassign the stored variable you should consider making it a constant (let)






                share|improve this answer


























                  5












                  5








                  5







                  The main difference is that you cannot assign something to the computed property since it has no setter. In this case the closure only gets called once and the return value gets stored in the variable so if the outcome doesn't change over time it is more efficient to use the stored variable rather than the computed one.



                  In general: computed properties should only be used if the value can be retrieved quickly.



                  Sidenote: If you don't change/reassign the stored variable you should consider making it a constant (let)






                  share|improve this answer













                  The main difference is that you cannot assign something to the computed property since it has no setter. In this case the closure only gets called once and the return value gets stored in the variable so if the outcome doesn't change over time it is more efficient to use the stored variable rather than the computed one.



                  In general: computed properties should only be used if the value can be retrieved quickly.



                  Sidenote: If you don't change/reassign the stored variable you should consider making it a constant (let)







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jul 20 '15 at 12:02









                  QbyteQbyte

                  8,09032242




                  8,09032242























                      5














                      Closure :



                        //closure
                      var pushBehavior: UIPushBehavior = {
                      let lazilyCreatedPush = UIPushBehavior()
                      lazilyCreatedPush.setAngle(50, magnitude: 50)
                      return lazilyCreatedPush
                      }()


                      At first time when pushBehavior variable called then block execute and value is saved in pushBehavior variable. after that whenever you call pushBehavior then those value are returned.



                      means only first-time block code executed and saved in this variable.
                      Also, you can store variable value whenever you want but after that, those value returned but if you declare as "let" then you can't change this value.



                      Computed property :



                      var pushBehavior: UIPushBehavior {
                      get{
                      let lazilyCreatedPush = UIPushBehavior()
                      lazilyCreatedPush.setAngle(50, magnitude: 50)
                      return lazilyCreatedPush
                      }
                      }


                      In computed property whenever you called pushBehavior variable then this block execute and value return. so every time block is executed.
                      and you can not declare variable as "let" keyword for pushBehavior variable.



                      So you can use this code as per your requirement.






                      share|improve this answer


























                      • The closure one will be initialized immediately whether or not you use it or not. It is not lazily initialize. BTW, capitalize the first word after a period, it makes reading a little bit more pleasant.

                        – Kent Liau
                        Dec 27 '16 at 3:58


















                      5














                      Closure :



                        //closure
                      var pushBehavior: UIPushBehavior = {
                      let lazilyCreatedPush = UIPushBehavior()
                      lazilyCreatedPush.setAngle(50, magnitude: 50)
                      return lazilyCreatedPush
                      }()


                      At first time when pushBehavior variable called then block execute and value is saved in pushBehavior variable. after that whenever you call pushBehavior then those value are returned.



                      means only first-time block code executed and saved in this variable.
                      Also, you can store variable value whenever you want but after that, those value returned but if you declare as "let" then you can't change this value.



                      Computed property :



                      var pushBehavior: UIPushBehavior {
                      get{
                      let lazilyCreatedPush = UIPushBehavior()
                      lazilyCreatedPush.setAngle(50, magnitude: 50)
                      return lazilyCreatedPush
                      }
                      }


                      In computed property whenever you called pushBehavior variable then this block execute and value return. so every time block is executed.
                      and you can not declare variable as "let" keyword for pushBehavior variable.



                      So you can use this code as per your requirement.






                      share|improve this answer


























                      • The closure one will be initialized immediately whether or not you use it or not. It is not lazily initialize. BTW, capitalize the first word after a period, it makes reading a little bit more pleasant.

                        – Kent Liau
                        Dec 27 '16 at 3:58
















                      5












                      5








                      5







                      Closure :



                        //closure
                      var pushBehavior: UIPushBehavior = {
                      let lazilyCreatedPush = UIPushBehavior()
                      lazilyCreatedPush.setAngle(50, magnitude: 50)
                      return lazilyCreatedPush
                      }()


                      At first time when pushBehavior variable called then block execute and value is saved in pushBehavior variable. after that whenever you call pushBehavior then those value are returned.



                      means only first-time block code executed and saved in this variable.
                      Also, you can store variable value whenever you want but after that, those value returned but if you declare as "let" then you can't change this value.



                      Computed property :



                      var pushBehavior: UIPushBehavior {
                      get{
                      let lazilyCreatedPush = UIPushBehavior()
                      lazilyCreatedPush.setAngle(50, magnitude: 50)
                      return lazilyCreatedPush
                      }
                      }


                      In computed property whenever you called pushBehavior variable then this block execute and value return. so every time block is executed.
                      and you can not declare variable as "let" keyword for pushBehavior variable.



                      So you can use this code as per your requirement.






                      share|improve this answer















                      Closure :



                        //closure
                      var pushBehavior: UIPushBehavior = {
                      let lazilyCreatedPush = UIPushBehavior()
                      lazilyCreatedPush.setAngle(50, magnitude: 50)
                      return lazilyCreatedPush
                      }()


                      At first time when pushBehavior variable called then block execute and value is saved in pushBehavior variable. after that whenever you call pushBehavior then those value are returned.



                      means only first-time block code executed and saved in this variable.
                      Also, you can store variable value whenever you want but after that, those value returned but if you declare as "let" then you can't change this value.



                      Computed property :



                      var pushBehavior: UIPushBehavior {
                      get{
                      let lazilyCreatedPush = UIPushBehavior()
                      lazilyCreatedPush.setAngle(50, magnitude: 50)
                      return lazilyCreatedPush
                      }
                      }


                      In computed property whenever you called pushBehavior variable then this block execute and value return. so every time block is executed.
                      and you can not declare variable as "let" keyword for pushBehavior variable.



                      So you can use this code as per your requirement.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Nov 25 '16 at 5:44

























                      answered Nov 23 '16 at 6:18









                      vikas prajapativikas prajapati

                      964921




                      964921













                      • The closure one will be initialized immediately whether or not you use it or not. It is not lazily initialize. BTW, capitalize the first word after a period, it makes reading a little bit more pleasant.

                        – Kent Liau
                        Dec 27 '16 at 3:58





















                      • The closure one will be initialized immediately whether or not you use it or not. It is not lazily initialize. BTW, capitalize the first word after a period, it makes reading a little bit more pleasant.

                        – Kent Liau
                        Dec 27 '16 at 3:58



















                      The closure one will be initialized immediately whether or not you use it or not. It is not lazily initialize. BTW, capitalize the first word after a period, it makes reading a little bit more pleasant.

                      – Kent Liau
                      Dec 27 '16 at 3:58







                      The closure one will be initialized immediately whether or not you use it or not. It is not lazily initialize. BTW, capitalize the first word after a period, it makes reading a little bit more pleasant.

                      – Kent Liau
                      Dec 27 '16 at 3:58













                      0














                      This isn't an answer, but it's just worth mentioning that for:




                      • A stored properties the value must be known after initialization. That happens either by defaulting or through initialization.

                      • A computed property's value isn't computed until it's accessed

                      • A lazy loaded property's value isn't defined until it's accessed


                      hence for both computed and lazy variables you can access self or stored properties with no worries.






                      share|improve this answer




























                        0














                        This isn't an answer, but it's just worth mentioning that for:




                        • A stored properties the value must be known after initialization. That happens either by defaulting or through initialization.

                        • A computed property's value isn't computed until it's accessed

                        • A lazy loaded property's value isn't defined until it's accessed


                        hence for both computed and lazy variables you can access self or stored properties with no worries.






                        share|improve this answer


























                          0












                          0








                          0







                          This isn't an answer, but it's just worth mentioning that for:




                          • A stored properties the value must be known after initialization. That happens either by defaulting or through initialization.

                          • A computed property's value isn't computed until it's accessed

                          • A lazy loaded property's value isn't defined until it's accessed


                          hence for both computed and lazy variables you can access self or stored properties with no worries.






                          share|improve this answer













                          This isn't an answer, but it's just worth mentioning that for:




                          • A stored properties the value must be known after initialization. That happens either by defaulting or through initialization.

                          • A computed property's value isn't computed until it's accessed

                          • A lazy loaded property's value isn't defined until it's accessed


                          hence for both computed and lazy variables you can access self or stored properties with no worries.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Jun 13 '18 at 20:34









                          HoneyHoney

                          10.1k661118




                          10.1k661118






























                              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%2f31515805%2fdifference-between-computed-property-and-property-set-with-closure%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







                              Popular posts from this blog

                              'app-layout' is not a known element: how to share Component with different Modules

                              android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

                              WPF add header to Image with URL pettitions [duplicate]