Finding sum of elements in Swift array

ArraysSwift

Arrays Problem Overview


What is the easiest (best) way to find the sum of an array of integers in swift? I have an array called multiples and I would like to know the sum of the multiples.

Arrays Solutions


Solution 1 - Arrays

This is the easiest/shortest method I can find.

Swift 3 and Swift 4:

let multiples = [...]
let sum = multiples.reduce(0, +)
print("Sum of Array is : ", sum)

Swift 2:

let multiples = [...]
sum = multiples.reduce(0, combine: +)

Some more info:

This uses Array's reduce method (documentation here), which allows you to "reduce a collection of elements down to a single value by recursively applying the provided closure". We give it 0 as the initial value, and then, essentially, the closure { $0 + $1 }. Of course, we can simplify that to a single plus sign, because that's how Swift rolls.

Solution 2 - Arrays

Swift 3+ one liner to sum properties of objects

var totalSum = scaleData.map({$0.points}).reduce(0, +)

Where points is the property in my custom object scaleData that I am trying to reduce

Solution 3 - Arrays

In Swift 4 You can also constrain the sequence elements to Numeric protocol to return the sum of all elements in the sequence as follow

extension Sequence where Element: Numeric {
    /// Returns the sum of all elements in the collection
    func sum() -> Element { return reduce(0, +) }
}

edit/update:

Xcode 10.2 • Swift 5 or later

We can simply constrain the sequence elements to the new AdditiveArithmetic protocol to return the sum of all elements in the collection

extension Sequence where Element: AdditiveArithmetic {
    func sum() -> Element {
        return reduce(.zero, +)
    }
}

Xcode 11 • Swift 5.1 or later

extension Sequence where Element: AdditiveArithmetic {
    func sum() -> Element { reduce(.zero, +) }
}

let numbers = [1,2,3]
numbers.sum()    // 6

let doubles = [1.5, 2.7, 3.0]
doubles.sum()    // 7.2

To sum a property of a custom object we can extend Sequence to take a predicate to return a value that conforms to AdditiveArithmetic:

extension Sequence  {
    func sum<T: AdditiveArithmetic>(_ predicate: (Element) -> T) -> T { reduce(.zero) { $0 + predicate($1) } }
}

Usage:

struct Product {
    let id: String
    let price: Decimal
}

let products: [Product] = [.init(id: "abc", price: 21.9),
                           .init(id: "xyz", price: 19.7),
                           .init(id: "jkl", price: 2.9)
]

products.sum(\.price)  // 44.5

Solution 4 - Arrays

Swift3 has changed to :

let multiples = [...]
sum = multiples.reduce(0, +)

Solution 5 - Arrays

Swift 4 example

class Employee {
    var salary: Int =  0
    init (_ salary: Int){
        self.salary = salary
    }
}

let employees = [Employee(100),Employee(300),Employee(600)]
var sumSalary = employees.reduce(0, {$0 + $1.salary}) //1000

Solution 6 - Arrays

This also works:

let arr = [1,2,3,4,5,6,7,8,9,10]
var sumedArr = arr.reduce(0, combine: {$0 + $1})
print(sumedArr)

The result will be: 55

Solution 7 - Arrays

Swift 3

If you have an array of generic objects and you want to sum some object property then:

class A: NSObject {
    var value = 0
    init(value: Int) {
       self.value = value
    }
}

let array = [A(value: 2), A(value: 4)]      
let sum = array.reduce(0, { $0 + $1.value })
//                           ^       ^
//                        $0=result  $1=next A object
print(sum) // 6 

Despite of the shorter form, many times you may prefer the classic for-cycle:

let array = [A(value: 2), A(value: 4)]
var sum = 0
array.forEach({ sum += $0.value}) 
// or
for element in array {
   sum += element.value
}

Solution 8 - Arrays

Swift 3, 4, and 5

Using reduce:

let totalAmount = yourTransactionsModelArray.reduce(0) { $0 + $1.amount}

Old fashioned way for understanding purposes:

for (var i = 0; i < n; i++) {
 sum = sum + Int(multiples[i])!
}

//where n = number of elements in the array

Solution 9 - Arrays

Swift 3.0

i had the same problem, i found on the documentation Apple this solution.

let numbers = [1, 2, 3, 4]
let addTwo: (Int, Int) -> Int = { x, y in x + y }
let numberSum = numbers.reduce(0, addTwo)
// 'numberSum' == 10

But, in my case i had a list of object, then i needed transform my value of my list:

let numberSum = self.list.map({$0.number_here}).reduce(0, { x, y in x + y })

this work for me.

Solution 10 - Arrays

A possible solution: define a prefix operator for it. Like the reduce "+/" operator as in APL (e.g. GNU APL)

A bit of a different approach here.

Using a protocol en generic type allows us to to use this operator on Double, Float and Int array types

protocol Number 
{
   func +(l: Self, r: Self) -> Self
   func -(l: Self, r: Self) -> Self
   func >(l: Self, r: Self) -> Bool
   func <(l: Self, r: Self) -> Bool
}

extension Double : Number {}
extension Float  : Number {}
extension Int    : Number {}

infix operator += {}

func += <T:Number> (inout left: T, right: T)
{
   left = left + right
}

prefix operator +/ {}

prefix func +/ <T:Number>(ar:[T]?) -> T?
{
    switch true
    {
    case ar == nil:
        return nil

    case ar!.isEmpty:
        return nil
    
    default:
        var result = ar![0]
        for n in 1..<ar!.count
        {
            result += ar![n]
        }
        return result
   }
}

use like so:

let nmbrs = [ 12.4, 35.6, 456.65, 43.45 ]
let intarr = [1, 34, 23, 54, 56, -67, 0, 44]

+/nmbrs     // 548.1
+/intarr    // 145

(updated for Swift 2.2, tested in Xcode Version 7.3)

Solution 11 - Arrays

Keep it simple...

var array = [1, 2, 3, 4, 5, 6, 7, 9, 0]
var n = 0
for i in array {
    n += i
}
print("My sum of elements is: \(n)")

Output:

> My sum of elements is: 37

Solution 12 - Arrays

another easy way of getting it done:

let sumOfMultiples = ar.reduce(0) { x, y in x + y }          
print(sumOfMultiples)

Solution 13 - Arrays

For me, it was like this using property

    let blueKills = match.blueTeam.participants.reduce(0, { (result, participant) -> Int in
        result + participant.kills
    })

Solution 14 - Arrays

@IBOutlet var valueSource: [MultipleIntBoundSource]!

private var allFieldsCount: Int {
    var sum = 0
    valueSource.forEach { sum += $0.count }
    return sum
}

used this one for nested parameters

Solution 15 - Arrays

For sum of elements in array of Objects

self.rankDataModelArray.flatMap{$0.count}.reduce(0, +)

Solution 16 - Arrays

Swift 3

From all the options displayed here, this is the one that worked for me.

let arr = [6,1,2,3,4,10,11]


var sumedArr = arr.reduce(0, { ($0 + $1)})
print(sumedArr)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionejLevView Question on Stackoverflow
Solution 1 - Arraysusername tbdView Answer on Stackoverflow
Solution 2 - ArraysJesus RodriguezView Answer on Stackoverflow
Solution 3 - ArraysLeo DabusView Answer on Stackoverflow
Solution 4 - ArraysdevelopermikeView Answer on Stackoverflow
Solution 5 - ArraysMobile DeveloperView Answer on Stackoverflow
Solution 6 - ArraysMarco AlmeidaView Answer on Stackoverflow
Solution 7 - ArraysLuca DavanzoView Answer on Stackoverflow
Solution 8 - ArraysNaishtaView Answer on Stackoverflow
Solution 9 - ArraysLuan AlmeidaView Answer on Stackoverflow
Solution 10 - ArraysTed van GaalenView Answer on Stackoverflow
Solution 11 - ArraysIsrael ManzoView Answer on Stackoverflow
Solution 12 - ArraysgeekMeView Answer on Stackoverflow
Solution 13 - ArraysAhmed SafadiView Answer on Stackoverflow
Solution 14 - ArraysAlexey LysenkoView Answer on Stackoverflow
Solution 15 - ArraysManish MahajanView Answer on Stackoverflow
Solution 16 - ArraysVictorView Answer on Stackoverflow