0

I have list of objects T and I want to calculate their sum (T objects)

var objects: Observable<List<T>>

T object has a method which return Int value. The main idea to get each object and prepare array of values (flatMap function). The next step will be reduce func with Int values.

let sum = values.reduce(0) { $0 + $1 }

Q: How to get each T object?

biloshkurskyi.ss
  • 1,358
  • 3
  • 15
  • 34

1 Answers1

0

Have a look at the solution below which is trying to demonstrate what you are trying to do, you might need a protocol for type T that has int property like the example below. You can try it with playground.

protocol Countable {

    var value: Int { get }
    init(value: Int)
}


class User: Countable {

    var value: Int = 0

    required convenience init(value: Int) {
        self.init()
        self.value = value
    }
}


class UserGroup<T: Countable> {

    func calculateTotal() {
        let users: [T] = [T(value: 2), T(value: 21)]
        let total = users.flatMap { ($0 as Countable).value }.reduce(0) { $0 + $1 }
        print("total", total)
    }
}

let userGroup = UserGroup<User>()
userGroup.calculateTotal()
kmarin
  • 332
  • 3
  • 8