How to use reduce function in swift for generic array?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







-2















I have the generic array like this -



let array = arrayOfElements as! [T]


I want to add elements of array using default(reduce) function of swift.



How can I do this?



I am using like below -



let result = array.reduce(0,+)


it shows error ambiguous reference to member '+'










share|improve this question

























  • Have a look at Apple's docs: developer.apple.com/documentation/swift/array/2298686-reduce

    – Daniel Springer
    Nov 23 '18 at 6:23











  • Could you describe in detail what you want to achieve? For now, you probably get that error, because the compiler does not know what T is, and if + is appliable to elements of type T. Anyway, that does not look like adding element to the array. It reduces the array to the single value (as the 'reduce' name implies).

    – Evgeniy
    Nov 23 '18 at 6:25






  • 1





    How would you expect the compiler to be able to sum a generic type?

    – Leo Dabus
    Nov 23 '18 at 6:26











  • You T should have +

    – Satish
    Nov 23 '18 at 6:26






  • 2





    Your generic Type would need to be constrained to the Numeric protocol

    – Leo Dabus
    Nov 23 '18 at 6:27


















-2















I have the generic array like this -



let array = arrayOfElements as! [T]


I want to add elements of array using default(reduce) function of swift.



How can I do this?



I am using like below -



let result = array.reduce(0,+)


it shows error ambiguous reference to member '+'










share|improve this question

























  • Have a look at Apple's docs: developer.apple.com/documentation/swift/array/2298686-reduce

    – Daniel Springer
    Nov 23 '18 at 6:23











  • Could you describe in detail what you want to achieve? For now, you probably get that error, because the compiler does not know what T is, and if + is appliable to elements of type T. Anyway, that does not look like adding element to the array. It reduces the array to the single value (as the 'reduce' name implies).

    – Evgeniy
    Nov 23 '18 at 6:25






  • 1





    How would you expect the compiler to be able to sum a generic type?

    – Leo Dabus
    Nov 23 '18 at 6:26











  • You T should have +

    – Satish
    Nov 23 '18 at 6:26






  • 2





    Your generic Type would need to be constrained to the Numeric protocol

    – Leo Dabus
    Nov 23 '18 at 6:27














-2












-2








-2








I have the generic array like this -



let array = arrayOfElements as! [T]


I want to add elements of array using default(reduce) function of swift.



How can I do this?



I am using like below -



let result = array.reduce(0,+)


it shows error ambiguous reference to member '+'










share|improve this question
















I have the generic array like this -



let array = arrayOfElements as! [T]


I want to add elements of array using default(reduce) function of swift.



How can I do this?



I am using like below -



let result = array.reduce(0,+)


it shows error ambiguous reference to member '+'







arrays swift generics






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 '18 at 9:16









Dávid Pásztor

23.4k83152




23.4k83152










asked Nov 23 '18 at 6:16









surajsuraj

12




12













  • Have a look at Apple's docs: developer.apple.com/documentation/swift/array/2298686-reduce

    – Daniel Springer
    Nov 23 '18 at 6:23











  • Could you describe in detail what you want to achieve? For now, you probably get that error, because the compiler does not know what T is, and if + is appliable to elements of type T. Anyway, that does not look like adding element to the array. It reduces the array to the single value (as the 'reduce' name implies).

    – Evgeniy
    Nov 23 '18 at 6:25






  • 1





    How would you expect the compiler to be able to sum a generic type?

    – Leo Dabus
    Nov 23 '18 at 6:26











  • You T should have +

    – Satish
    Nov 23 '18 at 6:26






  • 2





    Your generic Type would need to be constrained to the Numeric protocol

    – Leo Dabus
    Nov 23 '18 at 6:27



















  • Have a look at Apple's docs: developer.apple.com/documentation/swift/array/2298686-reduce

    – Daniel Springer
    Nov 23 '18 at 6:23











  • Could you describe in detail what you want to achieve? For now, you probably get that error, because the compiler does not know what T is, and if + is appliable to elements of type T. Anyway, that does not look like adding element to the array. It reduces the array to the single value (as the 'reduce' name implies).

    – Evgeniy
    Nov 23 '18 at 6:25






  • 1





    How would you expect the compiler to be able to sum a generic type?

    – Leo Dabus
    Nov 23 '18 at 6:26











  • You T should have +

    – Satish
    Nov 23 '18 at 6:26






  • 2





    Your generic Type would need to be constrained to the Numeric protocol

    – Leo Dabus
    Nov 23 '18 at 6:27

















Have a look at Apple's docs: developer.apple.com/documentation/swift/array/2298686-reduce

– Daniel Springer
Nov 23 '18 at 6:23





Have a look at Apple's docs: developer.apple.com/documentation/swift/array/2298686-reduce

– Daniel Springer
Nov 23 '18 at 6:23













Could you describe in detail what you want to achieve? For now, you probably get that error, because the compiler does not know what T is, and if + is appliable to elements of type T. Anyway, that does not look like adding element to the array. It reduces the array to the single value (as the 'reduce' name implies).

– Evgeniy
Nov 23 '18 at 6:25





Could you describe in detail what you want to achieve? For now, you probably get that error, because the compiler does not know what T is, and if + is appliable to elements of type T. Anyway, that does not look like adding element to the array. It reduces the array to the single value (as the 'reduce' name implies).

– Evgeniy
Nov 23 '18 at 6:25




1




1





How would you expect the compiler to be able to sum a generic type?

– Leo Dabus
Nov 23 '18 at 6:26





How would you expect the compiler to be able to sum a generic type?

– Leo Dabus
Nov 23 '18 at 6:26













You T should have +

– Satish
Nov 23 '18 at 6:26





You T should have +

– Satish
Nov 23 '18 at 6:26




2




2





Your generic Type would need to be constrained to the Numeric protocol

– Leo Dabus
Nov 23 '18 at 6:27





Your generic Type would need to be constrained to the Numeric protocol

– Leo Dabus
Nov 23 '18 at 6:27












2 Answers
2






active

oldest

votes


















2














How do you know that T is a type that can be added? T can be anything, can't it? What if T is Bool? True and False values can certainly not be added.



To be able to add Ts, the range of possible types for T must be limited. T must conform to the Numeric protocol. Since the Numeric protocol defines a + operator, we can be sure that whatever T is, as long as it conforms to Numeric, it can be added.



You could do something like this:



func sum<T: Numeric>(_ array: [T]) -> T {
return array.reduce(0, +)
}


Or an extension:



extension Sequence where Element : Numeric {
func sum() -> Element {
return reduce(0, +)
}
}


Note that in both cases, I have put a : Numeric constraint.






share|improve this answer































    1














    You can’t. T can be any type, including types that don’t have the + operator and/or can’t be created from the integer literal 0. Those requirements are provided by the Numeric protocol, so you can define your type parameter as <T: Numeric> to make this work






    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%2f53441485%2fhow-to-use-reduce-function-in-swift-for-generic-array%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      How do you know that T is a type that can be added? T can be anything, can't it? What if T is Bool? True and False values can certainly not be added.



      To be able to add Ts, the range of possible types for T must be limited. T must conform to the Numeric protocol. Since the Numeric protocol defines a + operator, we can be sure that whatever T is, as long as it conforms to Numeric, it can be added.



      You could do something like this:



      func sum<T: Numeric>(_ array: [T]) -> T {
      return array.reduce(0, +)
      }


      Or an extension:



      extension Sequence where Element : Numeric {
      func sum() -> Element {
      return reduce(0, +)
      }
      }


      Note that in both cases, I have put a : Numeric constraint.






      share|improve this answer




























        2














        How do you know that T is a type that can be added? T can be anything, can't it? What if T is Bool? True and False values can certainly not be added.



        To be able to add Ts, the range of possible types for T must be limited. T must conform to the Numeric protocol. Since the Numeric protocol defines a + operator, we can be sure that whatever T is, as long as it conforms to Numeric, it can be added.



        You could do something like this:



        func sum<T: Numeric>(_ array: [T]) -> T {
        return array.reduce(0, +)
        }


        Or an extension:



        extension Sequence where Element : Numeric {
        func sum() -> Element {
        return reduce(0, +)
        }
        }


        Note that in both cases, I have put a : Numeric constraint.






        share|improve this answer


























          2












          2








          2







          How do you know that T is a type that can be added? T can be anything, can't it? What if T is Bool? True and False values can certainly not be added.



          To be able to add Ts, the range of possible types for T must be limited. T must conform to the Numeric protocol. Since the Numeric protocol defines a + operator, we can be sure that whatever T is, as long as it conforms to Numeric, it can be added.



          You could do something like this:



          func sum<T: Numeric>(_ array: [T]) -> T {
          return array.reduce(0, +)
          }


          Or an extension:



          extension Sequence where Element : Numeric {
          func sum() -> Element {
          return reduce(0, +)
          }
          }


          Note that in both cases, I have put a : Numeric constraint.






          share|improve this answer













          How do you know that T is a type that can be added? T can be anything, can't it? What if T is Bool? True and False values can certainly not be added.



          To be able to add Ts, the range of possible types for T must be limited. T must conform to the Numeric protocol. Since the Numeric protocol defines a + operator, we can be sure that whatever T is, as long as it conforms to Numeric, it can be added.



          You could do something like this:



          func sum<T: Numeric>(_ array: [T]) -> T {
          return array.reduce(0, +)
          }


          Or an extension:



          extension Sequence where Element : Numeric {
          func sum() -> Element {
          return reduce(0, +)
          }
          }


          Note that in both cases, I have put a : Numeric constraint.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 23 '18 at 6:37









          SweeperSweeper

          73.4k1075144




          73.4k1075144

























              1














              You can’t. T can be any type, including types that don’t have the + operator and/or can’t be created from the integer literal 0. Those requirements are provided by the Numeric protocol, so you can define your type parameter as <T: Numeric> to make this work






              share|improve this answer




























                1














                You can’t. T can be any type, including types that don’t have the + operator and/or can’t be created from the integer literal 0. Those requirements are provided by the Numeric protocol, so you can define your type parameter as <T: Numeric> to make this work






                share|improve this answer


























                  1












                  1








                  1







                  You can’t. T can be any type, including types that don’t have the + operator and/or can’t be created from the integer literal 0. Those requirements are provided by the Numeric protocol, so you can define your type parameter as <T: Numeric> to make this work






                  share|improve this answer













                  You can’t. T can be any type, including types that don’t have the + operator and/or can’t be created from the integer literal 0. Those requirements are provided by the Numeric protocol, so you can define your type parameter as <T: Numeric> to make this work







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 23 '18 at 6:41









                  SvenSven

                  20.5k44568




                  20.5k44568






























                      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%2f53441485%2fhow-to-use-reduce-function-in-swift-for-generic-array%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

                      How to change which sound is reproduced for terminal bell?

                      Can I use Tabulator js library in my java Spring + Thymeleaf project?

                      Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents