4 Replies
      Latest reply on May 28, 2017 1:46 PM by John368
      John368 Level 1 Level 1 (0 points)

        Please tell a command, or a function, or a subscript, or a property with which I can sum the values of an array

         

        For example, there is array

         

        var arrayPoint = [1, 3, 12]
        

         

        I want to get a sum of values

         

        1 + 3 + 12

        • Re: Totalization of array values
          Claude31 Level 8 Level 8 (5,735 points)

          There is the built in reduce function for this :

           

          let sum = arrayPoint.reduce(0, combine: +)

           

          You start with 0 (or any other value you want) and add all items in array.

           

          If you want the product :

          prod = arrayPoint.reduce(1,combine: *)     // Here, need to start with 1

           

          You have other interesting functions on collections (map, filter, reduce); look  here

           

          h ttps://useyourloaf.com/blog/swift-guide-to-map-filter-reduce/

          1 of 1 people found this helpful
          • Re: Totalization of array values
            jorisvm Level 2 Level 2 (40 points)

            Hi,

             

            The shortest, best and standard Swift way is using reduce:

            
            var arrayPoint = [1, 3, 12]
            let arraySum = arrayPoint.reduce(0,+)
            print(arraySum)
            
            

             

            But if you want to have some fun and create your own code, this is a really nice case to create yourself a recursive function:

            
            func sumArray(_ numbers: [Int]) -> Int {
                var sumTheseNumbers = numbers
                if sumTheseNumbers.count <= 0 {
                    return 0
                } else {
                    let firstNumber = sumTheseNumbers.removeFirst()
                    return  firstNumber + sumArray(sumTheseNumbers)
                }
            }
            var arrayPoint = [1, 3, 12]
            let theSum = sumArray(arrayPoint)
            print(theSum)
            

             

            Have fun,

            Joris

            1 of 1 people found this helpful