Search code examples
arraysswiftsumreduce

Sum of Array containing custom class (Swift)


i am figuring out a way to get the sum of values of classes which are contained in an array. My setup is as follows:

class CustomClass {
    var value: Int?
    init(value: Int) {
       self.value = value
    }
}

let object1 = CustomClass(value: 2)
let object2 = CustomClass(value: 4)
let object3 = CustomClass(value: 8)

let array: [CustomClass] = [object1, object2, object3]

My current solution is as follows:

var sumArray = [Int]()
for object in array {
    sumArray.append(object.value!)
}
let sum = sumArray.reduce(0, +)

The problem is that it gets very complex with classes with many other values, does anybody know a better solution?


Solution

  • You can use a single reduce on array.

    let sumOfValues = array.reduce({$0 += ($1.value ?? 0)})